Skip to content

Lab 7.1. Arduino digitalWrite, analogWrite

Estimated time to complete this lab: 1 hour

Objectives

At the end of this self-learning lab, you should be able to:

  • Write a publisher and subscriber node in Python

Background. What is Arduino?

Arduino Uno

  • Arduino is an open-source platform used for building electronics projects. It consists of the Arduino board and the Arduino software.
  • Arduino board is a physical programmable circuit board, or simply called a microcontroller (MCU for microcontroller unit).
  • There are many different types of Arduino boards with different characteristics, including Arduino UNO, Arduino NANO and Arduino MEGA.
  • We will be using Arduino UNO in the labs in this chapter.
I am a programmer in M2, why do I need to learn about these electronics stuff?

As a programmer, you need to learn how to write software to communicate with your lower layers (the board)!

Prerequistes

  • Arduino runs on a modified version of C++. But even if you haven’t learnt C++ before, the examples below should still make sense. Still, you are recommended (but not required) to see this tutorial on the m2_wiki about C++ programming afterwards.

Section 1. Arduino IDE

Integrated Development Environment (IDE) is a more advanced text editor for writing code.

Installation instructions

  • Download the Arduino IDE from Arduino official website: https://www.arduino.cc/en/Main/Software
  • Please do not use the Arduino Web Editor. It is impossible to install third-party hardwares and libraries, which you may use later on after training.

Warning

Please DON'T install from official Ubuntu package. It is version 1.0.5, released at 2013-05-15.

  • In most cases, you will want to click "Linux 64 bits". A .tar.xz archive file will be downloaded. Decompress it.
  • Inside the folder you should see arduino. Double click it, select "run", and the Arduino IDE will be launched.

Warning

Please DON'T install from Microsoft store. Use Windows Installer instead.

  • Click and download "Windows Installer, for Windows XP and up".
  • Run the installer, follow the instructions, and the Arduino IDE will be installed.
  • Click and download "Mac OS X 10.8 Mountain Lion or newer".
  • Run the installer, follow the instructions, and the Arduino IDE will be installed.
  • Open up the Arduino IDE you installed. It contains:
    • a text editor for writing code
    • a message area, text console
    • a toolbar with buttons for common functions, series of menus
  • It connects to the Arduino board to upload programs and communicate with them.

Arduino IDE

Meaning of buttons in IDE interface:

  • Verify Verify 
    • Checks your code for errors. Will not upload your code to the board.
  • Upload Upload
    • Compiles your code and uploads it to the board. See uploading below for details.
  • New New
    • Creates a new sketch.
  • Open Open
    • Presents a menu of all the sketches in your sketchbook. Clicking one will open it within the current window overwriting its content.
  • Save Save
    • Saves your sketch.

Inside the file "PlaceForCode", it is your coding area. There are some functions:

  • void setup(): It is a function the Arduino boards run once at startup.
  • void loop(): It will run repeatedly after the setup() function has completed.

The program flow is summarized below:

Program Flow

Section Check Box:

  • What is Arduino IDE and its usage
  • Meaning of buttons in IDE interfaces
  • void setup() { … }
  • void loop() { … }

There is an LED on the Arduino board. Let’s write a program to control it!

  • Click File → Examples → 01. Basics → Blink.
  • Scroll past the comments at the top, and you should see the following code (comments removed for space):
  • The comments provided in the actual code file should be self-explanatory.
// setup() runs once when you press reset or power the board
void setup() {
    (LED_BUILTIN, OUTPUT);
}
// loop() runs over and over again forever
void loop() {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(1000);
    digitalWrite(LED_BUILTIN, LOW);
    delay(1000);
}
Line-by-line explanations of code:
  • As said in the previous section, the program starts from the setup() function in line 1. { and } on line 1 and 3 defines the scope of setup() function.
  • Inside this setup() function, on line 2, we have pinMode(LED_BUILTIN, OUTPUT); written there. This line is an instruction that tells the board to do something.
    • This instruction is called a statement. Usually a statement fit in exactly one line. Each statement MUST end with a semicolon to denote that the statement has finished. *. pinMode(LED_BUILTIN, OUTPUT)
    • It configures a pin as either an input or an output.
    • Input means you use the pin to detect the voltage on the external circuit connected to that pin (will be discussed later), while output means you use the pin to output a voltage to control something.
    • LED_BUILTIN and OUTPUT are the two parameters that are required by pinMode(). LED_BUILTIN means you are referring to pin LED_BUILTIN. Thus, you can change it to another pin, so that the pin mode of another pin can be defined. OUTPUT means you want the pin you have stated in the 1st statement to be in output mode. You can change it to INPUT so the pin is defined to be in INPUT mode.
    • Noted that the M in pinMode must be in capital letter. The word OUTPUT and INPUT must be in capital letter too.
  • After the setup is finished, the program will then go into the loop() function. Line 6-9 are the 4 statements inside loop().
  • digitalWrite(LED_BUILTIN, HIGH)
    • It means supplying 3.3 volts (HIGH logic signal) to pin LED_BUILTIN from 0 volt (LOW logic signal) before this statement is executed.
    • digital in digitalWrite means you can only write either HIGH or LOW value to the pin, corresponding to 1 or 0 for computer.
    • Write in digitalWrite means you are writing a value a pin, rather than reading a value. The opposite of this statement is digitalRead(pin) which will be discussed later.
    • Just like in pinMode(LED_BUILTIN, OUTPUT);, LED_BUILTIN and HIGH in digitalWrite(LED_BUILTIN, HIGH) are the two parameters for digitalWrites.
    • The statement pinMode(LED_BUILTIN, OUTPUT); must be executed before digitalWrite(LED_BUILTIN, HIGH); , otherwise you may encounter unexpected situations.
  • delay(1000);
    • It pauses the program for the amount of time (in milliseconds) specified as parameter.
    • 1000 means 1000 milliseconds, which is equal to 1 second.
  • digitalWrite(LED_BUILTIN, LOW)
    • Similar to digitalWrite(LED_BUILTIN, HIGH);, it controls the voltage output of pin LED_BUILTIN. This time, it assigns a LOWvalue to pin LED_BUILTIN, which means supplying 0 volt to the pin.
  • Comment - useful but also useless
    • You may notice that there are sentences after the statements. They are comments.
    • Comments are lines in the program that are used to inform yourself or others about the way the program works. They are ignored by the STM32. Thus, comments are useful for yourself to view the code, but useless for the board to execute the code.
    • Comments only purpose are to help you understand (or remember) how your program works or to inform others how your program works. There are two different ways of marking a line as a comment.
    • Using double slash //
    • The comment starts after the //. It is a single line comment. Anything after the slashes is a comment to the end of the line.
    • Using /* and */
    • The comment starts after /*, all the way through lines and sentences to */. Unlike the double slash, it is multiline comment, using to comment out whole blocks of code.

Section Check Box:

  • pinMode(pin , mode)
  • semi-colon ;
  • digitalWrite(pin , value)
  • delay(milliseconds)
  • Comment // or /* … */

Upload the Code to board

Let's upload the code to the Arduino board.

  • You need a suitable USB cable and the Arduino board.

(Arduino_Tutorials)_Arduino_and_USB

  • Plug in the USB wire to Arduino board and the other side to the computer. A LED on the board turned on shows that the it is working.
  • If your Arduino IDE is on a Linux VM, you will also need to attach the Arduino device to the VM. Choose the Arduino from the list of USB devices. Note that the name may (very likely) be different from the one shown below.

(Arduino_Tutorials)_VM_Attach

Tip

If you are not sure which device is the Arduino, try to detach the USB cable, check the list, then reattach the cable to see which device is newly plugged.

  • Return to the Arduino IDE. Before we upload the code to the board, we need to check that the IDE knows what development board we are using and which port is it connected to.

    • Press Tools → Port. If there are more than one choices of port, just randomly select one. If it is not the port you have you board connected to, error will be shown when you upload your code to the board. Just try and find out the one which gives no error and that is the desired port.
    • Now, select "Tools" → "Board" → "Arduino/Genuino UNO" in toolbar.
    • On Linux, you should also run $ sudo chmod 777 /dev/ttyUSB0 on a terminal. Replace /dev/ttyUSB0 with the port name in the Arduino IDE.
  • After the preparation steps are done, we can now upload our code to the board. Click the upload button and wait for it to compile...

Done Uploading

  • When you see the words "Done uploading", it means that your code has successfully uploaded to the board. You should now see another LED on the board blinking in a one second interval.

Bug

Problem uploading to board

  • If this error message – "Problem uploading to board" happens, there should be no error in your code. This problem is arising from the data transfer between the board and computer. Simply unplug and plug the USB again, and reuploading the code can usually solve most problems.

Try it yourself

SOS

Write an Arduino code to light up LED 13 on the board, sending out the S.O.S. signal. In Morse code, "S" is represented by 3 short flashes, while "O" is represented by 3 long flashes.

Section 3. Dim an LED using PWM and analogWrite

You may notice that the brightness of the LED on the Arduino is fixed. This is because the voltage provided by digitalWrite can only be HIGH or LOW, and we cannot set a "medium" brightness with it. To achieve "medium" brightness, we need to use PWM.

  • PWM is the abbreviation of Pulse Width Modulation.

PWM

There are 2 major functions of PWM:

  • The length of the pulse width can be used to encoded data. For example, Servo motor uses PWM to acquire the desire position.
  • PWM wave can be used to control the power delivered to a desired value. In the example below, the brightness of an LED can be adjusted even though only HIGH and LOW are delivered from the Arduino. You also need to use this to control the speed of a motor.

To use PWM in Arduino, we can use analogWrite():

  • Click File → Examples → 03. Basics → Fade.
int led = 9;            // the PWM pin the LED is attached to
int brightness = 0;     // how bright the LED is
int fadeAmount = 5;     // how many points to fade the LED by

void setup() {
    pinMode(led, OUTPUT);
}

void loop() {
    analogWrite(led, brightness);

    brightness = brightness + fadeAmount;

    if (brightness <= 0 || brightness >= 255) {
        fadeAmount = -fadeAmount;
    }
    // wait for 30 milliseconds to see the dimming effect
    delay(30);
}
analogWrite(led, brightness);
Write a PWM with brightness to led.
  • Note that you cannot use the LED on the Arduino board (pin 13) to perform fade as that pin does not support PWM (see appendix for more). Therefore, you need to attach an LED to the board by yourself to a pin that supports PWM, e.g. pin 9.
    • A pin supports PWM if it has the ~ character printed next to it.
  • Connect the setup like below (long pin of LED to pin 9, short pin to GND), upload the program, and you should see the brightness of the LED fading.

(Arduino_Tutorials)_Arduino_LED_Connection

Checklist

Checklist

Congratulations! You have learnt some of the basics of Arduino!

  • What is Arduino
  • Uploading code to the Arduino Board
  • digitalWrite, analogWrite

References