Arduino 101
Basic Programming Concepts

Nick Borko

September 28, 2013

Creative Commons Logo for BY-NC-SA
Except where otherwise noted, this work is licensed under
http://creativecommons.org/licenses/by-nc-sa/3.0

Agenda

  • Introduction
  • Arduino Programming Basics
    • Minimum Program Structure
    • Input, Output and Delays
  • C++ Programming Concepts
    • Types and Variables
    • Conditionals, Loops and Functions
  • Conclusion

Arduino Programming Basics

  • Arduino programs are written in C++
  • Arduino programs are built on the Arduino Core
    • Handles boilerplate initialization code
    • Provides high-level interfaces to control AVR functions
    • Automatically linked to the Arduino program
  • Compiling, linking and uploading is handled by the IDE

Arduino Programming Basics:

Arduino Program Structure

  • The minimum Arduino program defines 2 functions:
    • setup() is called when the program starts and runs once, normally used for pin and variable initialization
    • loop() is called continuously after setup() finishes executing (i.e., as an endless loop)
  • Every Arduino program must define both setup() and loop(), although either (or both!) may be empty

Arduino Programming Basics:

Arduino Program Structure

  • The minimum Arduino program defines 2 functions:
    // A minimal Arduino program
    // NOTE: Comments start with //
    void setup () {
      // do nothing one time!
    }
    
    void loop() {
      // do nothing over and over!
    }
  • This program is remarkably uninteresting

Arduino Programming Basics:

Input and Output

  • The Arduino can also run more interesting programs by reading input and sending output (the whole point to programming!)
  • Input is read from and output is sent to pins on the AVR microprocessor
  • The Arduino board breaks out these pins to headers, which can be used to read and write digital and analog signals

Arduino Programming Basics:

Input and Output

  • Arduino digital input/output pins are numbered 0-13 (for a total of 14 pins)
    • Pins 0 and 1 are reserved for serial communication (don't use these!)
    • Pins 2 and 3 can be configured for external interrupts
    • Pins 3, 5, 6, 9, 10 and 11 are capable of Pulse Width Modulation (PWM) analog output
    • Pins 10-13 can be used for SPI (serial) communication

Arduino Programming Basics:

Input and Output

  • Arduino analog input pins are numbered A0-A5 (for a total of 6 pins)
    • Can read an analog values between 0 and 1023 based on a reference voltage (labeled AREF on the Arduino)
    • Can also be used as additional digital input/output pins, numbered 14-19
    • Pins A4 and A5 can be used for TWI ("2-wire" interface), compatible with I2C (Inter-Integrated Circuit)

Arduino Programming Basics:

Input and Output

  • Pins must be set up for input or output before they can be used:

    pinMode(PIN, MODE);

    • PIN is a pin number 0-19 or A0-A5
    • MODE is either INPUT or OUTPUT
  • Usually called in the setup() function
  • You don't need to set the pin mode for a pin you're not using (i.e. not connected)

Arduino Programming Basics:

Input and Output

  • Example from the Blink sketch
    void setup() {
      // initialize the digital pin as an output.
      // Pin 13 has an LED connected on most Arduino boards:
      pinMode(13, OUTPUT);
    }

Arduino Programming Basics:

Input and Output

  • Digital input is read from a selected pin:

    value = digitalRead(PIN);

    • PIN is a pin number 0-13
    • value is returned as either LOW or HIGH
  • Digital output is written to a selected pin:

    digitalWrite(PIN, VALUE);

    • PIN is a pin number 0-19
    • VALUE is either LOW or HIGH

Arduino Programming Basics:

Input and Output

  • Example from the Blink sketch
    void loop() {
      digitalWrite(13, HIGH); // set the LED on
      delay(1000);            // wait for a second
      digitalWrite(13, LOW);  // set the LED off
      delay(1000);            // wait for a second
    }

Arduino Programming Basics:

Input and Output

  • Analog input is read from an analog pin:

    value = analogRead(PIN);

    • PIN is a pin number A0-A5 (or 14-19)
    • value is returned as a number 0-1023
  • Analog output is written to a PWM pin:

    analogWrite(PIN, VALUE);

    • PIN is a pin number 3, 5, 6, 9, 10 or 11
    • VALUE is a number from 0 to 255

Arduino Programming Basics:

Input and Output

  • There are other ways to do input and output:
    • tone()
    • shiftIn()
    • shiftOut()
    • pulseIn()
    • SPI, SoftwareSerial and Wire libraries
  • Except for tone(), we won't be covering these in this workshop

Arduino Programming Basics:

Killing Time

  • Simple sketches can use the delay() and delayMicroseconds() functions
    • delay() takes a numerical argument for the number of milliseconds (0.001 seconds) to delay execution
    • delayMicroseconds() takes a numerical argument for the number of microseconds (0.000001 seconds), up to 16k microseconds
  • Program execution "halts" during a delay, so use with care

Arduino Programming Basics:

Killing Time

  • Example from the Blink sketch
    void loop() {
      digitalWrite(13, HIGH); // set the LED on
      delay(1000);            // wait for a second
      digitalWrite(13, LOW);  // set the LED off
      delay(1000);            // wait for a second
    }

C++ Programming Concepts

  • Although the programming environment is based on Processing, the programming language for Arduino is C++
    • Variables are typed (strongly) and must be declared before use
    • Statements end with a semicolon ;
    • Curly braces {} are used to mark program blocks
    • Single line comments begin with //, multiline comments are marked with /* ... */

C++ Programming Concepts

Types and Variables

  • All variables and data have a type
    • C++ types: int, float, char, bool, void, et. al.
    • Arduino types: boolean, byte, string, array
  • All variables must be declared before use
    • Variable declarations can appear anywhere, as long as it's before a reference
    • Variables can be initialized in the declaration
    • Variables are scoped by execution block
  • Variable names start with a letter or _

C++ Programming Concepts:

Types and Variables

  • Variables can be assigned values and used in expressions
    int a = 2;
    int b = 3;
    int c;
    c = a + b;     // c now has a value of 5
    c = b * 4;     // c now has a value of 12
    a = a + 1;     // a now has a value of 3
    c = a * b – c; // c now has a value of -3
  • If you haven't programmed before, don't worry about it; you won't be writing code

C++ Programming Concepts:

Types and Variables

  • Example from the Fade sketch
    int brightness = 0; // how bright the LED is
    int fadeAmount = 5; // how many points to fade the LED by
    
    void setup() {
      // declare pin 9 to be an output:
      pinMode(9, OUTPUT);
    }
    
    void loop() {
      // set the brightness of pin 9:
      analogWrite(9, brightness);
      // change the brightness for next time through the loop:
      brightness = brightness + fadeAmount;
      // reverse the direction of the fading at the ends of the fade:
      if (brightness == 0 || brightness == 255) {
        fadeAmount = -fadeAmount ;
      }
      // wait for 30 milliseconds to see the dimming effect
      delay(30);
    }

C++ Programming Concepts

Conditionals

  • C++ has if/else and switch/case control structures, but we will only cover if/else
  • The if/else statements allow conditional execution of code
    • If an expression evaluates to "true," then the code block following an if statement is executed
    • If the expression evaluates to "false," then the code block follow the adjoining else statement is executed

C++ Programming Concepts

Conditionals

  • All expressions evaluate to "true" or "false," where "false" is defined as "0" (zero), and "true" is anything else
  • Boolean expressions evaluate to true or false
    • Equality (==) and inequality (!=)
    • Numerical comparisons (<, >, <=, >=)
    • Boolean operators not (!), and (&&), or (||)
    • Note that string comparisons use functions

C++ Programming Concepts:

Conditionals

  • Example from the Fade sketch
    int brightness = 0; // how bright the LED is
    int fadeAmount = 5; // how many points to fade the LED by
    
    void setup() {
      // declare pin 9 to be an output:
      pinMode(9, OUTPUT);
    }
    
    void loop() {
      // set the brightness of pin 9:
      analogWrite(9, brightness);
      // change the brightness for next time through the loop:
      brightness = brightness + fadeAmount;
      // reverse the direction of the fading at the ends of the fade:
      if (brightness == 0 || brightness == 255) {
        fadeAmount = -fadeAmount ;
      }
      // wait for 30 milliseconds to see the dimming effect
      delay(30);
    }

C++ Programming Concepts

Loops

  • Loops allow a block of code to be executed more than once without duplicating code
  • C++ supports for and while loops
  • You won't be writing any code for this workshop, but you do need to recognize loops in code

C++ Programming Concepts

Loops

  • The while loop executes a code block as long as the condition is true
    while(condition) {
      // code block
    }
  • A do...while construct is also available
    do {
      // code block
    } while(condition);

C++ Programming Concepts

Loops

  • The for loop is just a modified while loop
    for(init; condition; loop statement) {
      // code block
    }
    • init is a statement that is executed once before the loop begins
    • The code block is executed as long as the condition is true (as in a while loop)
    • The loop statement is executed at the end of each iteration of the code block

C++ Programming Concepts

Loops

  • The for loop is just a modified while loop
    for(init; condition; loop statement) {
      // code block
    }
    • This is exactly equivalent to:
      init;
      while(condition) {
        // code block
        loop statement;
      }

C++ Programming Concepts

Functions

  • A function is a group of statements that is executed when it is called from some point of the program
  • Functions allow you to execute the same code block at different places in your program
  • You are already writing functions, setup() and loop()

C++ Programming Concepts

Functions

  • Functions can take parameters and return values
  • Function examples:
    void blinkLed(int pin, int milliseconds) {
      digitalWrite(pin, HIGH);
      delay(milliseconds);
      digitalWrite(pin, LOW);
    }
    
    int celsuisToFahrenheit(int degrees) {
      return degrees * 1.8 + 32;
    }

Conclusion

  • Arduino Programming Basics
    • Minimum Program Structure
    • Input, Output and Delays
  • C++ Programming Concepts
    • Types and Variables
    • Conditionals, Loops and Functions
  • Next Steps: Get your hands dirty!

This presentation is available online at:
http://nborko.github.io/arduino101/

All source files used for this workshop are available online at:
https://github.com/nborko/arduino101