Arduino Foundations

43
Arduino foundations: sketch basics, what’s on board, more programming http://arduino.cc/en/ Tutorial/Foundations

description

Based on the Arduino foundations tutorial at http://arduino.cc/en/Tutorial/Foundations

Transcript of Arduino Foundations

Page 1: Arduino Foundations

Arduino foundations: sketch basics, what’s on board, more programming

http://arduino.cc/en/Tutorial/Foundations

Page 2: Arduino Foundations

Basics

What’s a sketch and how does it work?

Page 3: Arduino Foundations

Sketch: comments and variables

• A sketch is the name Arduino uses for a program• Comments are used to explain what the program

does:– Use /* blah */ to comment out an area of code– Use // to add a comment to the end of a line of code

• A variable is a place for storing data:– type name = value;– int ledPin = 13;– Every time ledPin is referred to in code, value is retrieved– Can also change variable value in code

Page 4: Arduino Foundations

Sketch: functions

• Functions are named pieces of code that can be used from elsewhere in a sketch:– setup(), loop(), pinMode()

• First line of a function provides info about it, like its name (e.g. setup), and the text before / after the name specify its return type and parameters:

void setup(){[body of function]}

Page 5: Arduino Foundations

Sketch: functions (2)

• Can call a pre-defined function as part of the Arduino language or functions defined in your sketch:– e.g. pinMode(ledPin, OUTPUT); calls pinMode()

with the parameters ledPin and OUTPUT

• We’ll now describe some sample functions that you may have seen already

Page 6: Arduino Foundations

Function: pinmode()

• The pinMode() function configures a pin as either an input or an output

• To use it, you pass it the number of the pin to configure and the constant INPUT or OUTPUT

• When configured as an input, a pin can detect the state of a sensor like a pushbutton

• As an output, it can drive a device like an LED

Page 7: Arduino Foundations

Functions: digitalWrite(), delay()

• digitalWrite() outputs a value on a pin• For example, the line:

– digitalWrite(ledPin, HIGH);

sets the ledPin (pin 13) to HIGH, or 5 volts• Writing a LOW to the pin connects it to ground, or 0 volts

• delay() causes the Arduino to wait for the specified number of milliseconds before continuing on to the next line

• There are 1000 milliseconds in a second, so the line:– delay(1000);

creates a one second delay

Page 8: Arduino Foundations

Special functions: setup(), loop()

• There are two special functions that are a part of every Arduino sketch: setup() and loop():– setup() is called once, when the sketch starts

• It's a good place to do setup tasks like setting pin modes or initializing libraries

– The loop() function is called over and over and is heart of most sketches

• You need to include both functions in your sketch, even if you don't need them for anything

Page 9: Arduino Foundations

Exercises, based on ‘blink’ code

1. Change the code so that the LED is on for 100 milliseconds and off for 1000

2. Change the code so that the LED turns on when the sketch starts and stays on

Page 10: Arduino Foundations

Problem

• Write a sketch that turns on and off the onboard LED (pin 13) in the Morse code-style SOS sequence ‘· · · — — — · · ·’, assuming that a unit is of one second duration, and Morse code is composed of the following five elements:– short mark, dot or 'dit' (·) — 'dot duration' is one unit long;– longer mark, dash or 'dah' (–) — three units long;– inter-element gap between the dots and dashes within a character

— one unit long;– short gap (between letters) — three units long;– medium gap (between words) — seven units long.– http://en.wikipedia.org/wiki/

Morse_code#Representation.2C_timing_and_speeds

Page 11: Arduino Foundations

Morse code codeint pin = 13;

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

void loop(){ dot(); dot(); dot(); delay(2000); // plus last one second delay from the dot function = 3 dash(); dash(); dash(); delay(2000); // plus last one second delay from the dash function = 3 dot(); dot(); dot(); delay(6000); // plus last one second delay from the dot function = 7}

Page 12: Arduino Foundations

Morse code code (2)void dot(){ digitalWrite(pin, HIGH); delay(1000); digitalWrite(pin, LOW); delay(1000);}

void dash(){ digitalWrite(pin, HIGH); delay(3000); digitalWrite(pin, LOW); delay(1000);}

Page 13: Arduino Foundations

Overview

• First, we have the dot() and dash() functions that do the actual blinking

• Second, there's the pin variable which the functions use to determine which pin to use

• Finally, there's the call to pinMode() that initialises the pin as an output

Page 14: Arduino Foundations

On the microcontroller

Pins and memory

Page 15: Arduino Foundations

Configuring digital pins

• Note: the vast majority of Arduino (Atmega) analog pins may be configured, and used, in exactly the same manner as digital pins

• We’ll look at:– Properties of pins configured as INPUT– Pull-up resistors– Properties of pins configured as OUTPUT

Page 16: Arduino Foundations

Properties of pins configured as INPUT

• Arduino pins default to INPUT:– Don’t need to be explicitly defined as INPUT-type

using pinMode()• Input pins are high impedance (order of MW):– Will draw little current (order of mA)– Suitable for low current apps like capacitive touch

sensors, FSRs, phototransistors / photodiodes, etc.• But with nothing connected, become sensitive

to external noise from the environment

Page 17: Arduino Foundations

Pull-up resistors

• Used to steer an input to a particular (default) state if no input is present

• Could add a pull-up resistor to +5 volts or a pull-down resistor to 0 volts, e.g. using a 10 kΩ value

• There are built-in 20 kΩ pull-up resistors on the Atmega chips, which can be enabled via software:– pinMode(pinX, INPUT); // set pin to input– digitalWrite(pinX, HIGH); // turn on pull-up resistors

Page 18: Arduino Foundations

Pull-up resistors (2)

• Pull-ups will provide enough current to dimly light LEDs on a pin configured (by default) in INPUT mode:– So if an LED lights dimly, the pin probably hasn’t

been set to OUTPUT mode

Page 19: Arduino Foundations

Switching from INPUT to OUTPUT

• Note also that the pull-up resistors are controlled by the same registers (internal chip memory locations) that control whether a pin is HIGH or LOW

• Consequently, a pin that is configured to have pull-up resistors turned on when the pin is an INPUT will have the pin configured as HIGH if the pin is then switched to an OUTPUT with pinMode()

• This works in the other direction as well, and an output pin that is left in a HIGH state will have the pull-up resistors set if switched to an input with pinMode()

Page 20: Arduino Foundations

Special case: digital input pin 13

• Digital pin 13 is harder to use as a digital input than the other pins because it has an LED and resistor attached to it that's soldered to the board on most Arduinos

• If you enable its internal 20 kΩ pull-up resistor, it will hang at around 1.7 V instead of the expected 5 V because the onboard LED and series resistor pull the voltage level down, meaning it always returns LOW

• If you must use pin 13 as a digital input, use an external pull down resistor…

Page 21: Arduino Foundations

Properties of pins configured as OUTPUT

• Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state:– Can provide a substantial current to other circuits,

up to 40 mA– Enough to brightly light up an LED (via a series

resistor), or run many types of sensors, but not a motor, for example

Page 22: Arduino Foundations

Properties of pins configured as OUTPUT (2)

• Short circuits on Arduino pins, or attempting to run high current devices, can damage or destroy the output transistors in the pin, or damage the entire Atmega chip:– Often this will result in a "dead" pin but the remaining

chip will still function• It is a good idea to connect OUTPUT pins to other

devices with 470 Ω or 1kΩ resistors, unless maximum current draw from pins is required for a particular app

Page 23: Arduino Foundations

Analog input pins / ADC

• The Atmega controllers used for the Arduino contain an onboard 6-channel analog-to-digital (A/D) converter:– The converter has 10 bit resolution, returning integers

from 0 to 1023• While the main function of the analog pins is to

read analog sensors, the analog pins also have all the functionality of general purpose input/output (GPIO) pins (the same as digital pins 0 – 13)

Page 24: Arduino Foundations

Pin mapping

• The analog pins can be used identically to the digital pins, using the aliases A0 (for analog input 0), A1, etc.

• For example, the code would look like this to set analog pin 0 to an output, and to set it HIGH:– pinMode(A0, OUTPUT);– digitalWrite(A0, HIGH);

Page 25: Arduino Foundations

Pull-up resistors for analog pins

• The analog pins also have pull-up resistors, which work identically to pull-up resistors on the digital pins

• They are enabled by issuing a command such as:– digitalWrite(A0, HIGH); // set pull-up on analog pin 0

while the pin is an input• Be aware however that turning on a pull-up will affect

the values reported by analogRead()• Note that the same issue as for digital pins applies to

analog pins when switching from INPUT to OUTPUT as regards the pull-up settings

Page 26: Arduino Foundations

Pulse width modulation

Page 27: Arduino Foundations

Memory on the Arduino

• Three pools of memory in the microcontroller used on Arduino boards (ATmega168):– Flash memory (program space) is where the sketch is

stored [16 kbytes non-volatile, 2k used for bootloader]– SRAM (static random access memory) is where the

sketch creates and manipulates variables when it runs [1 kbyte volatile]

– EEPROM is memory space that programmers can use to store long-term information [512 bytes non-volatile]

Page 28: Arduino Foundations

SRAM limits

• Not much SRAM available, so can be used up quite quickly by defining strings, etc.:– char message[] = "I support the Arduino project.";

• If program not running successfully, it may be that you’ve run out of SRAM:– Try commenting out string definitions, lookup tables, large

arrays to see if it works without them– If interfacing with a PC, move data and/or calculations to

the PC instead if possible– Store strings or data in flash memory instead with

PROGMEM

Page 29: Arduino Foundations

Programming techniques

Variables, functions and libraries

Page 30: Arduino Foundations

Variables

• As mentioned, a variable is a place to store a piece of data

• A variable has other advantages over a value like a number, once it’s declared (int pin = 13;)

• Most importantly, you can change the value of a variable using an assignment (indicated by an equals sign), for example:– pin = 12;

• The name of the variable is permanently associated with a type; only its value changes

Page 31: Arduino Foundations

Assigning a variable to another

• When you assign one variable to another, you're making a copy of its value and storing that copy in the location in memory associated with the other variable

• Changing one has no effect on the other• For example, after:– int pin = 13;– int pin2 = pin;– pin = 12;

only pin has the value 12; pin2 is still 13

Page 32: Arduino Foundations

Scope: global

• If you want to be able to use a variable anywhere in your program, declare it at top of your code (a global variable):

int pin = 13;void setup() { pin = 12; pinMode(pin, OUTPUT); }void loop() { digitalWrite(pin, HIGH); }

• Both functions are using pin and referring to the same variable, so that changing in one will affect value in the other

• Here, the digitalWrite() function called from loop() will be passed a value of 12, since that was assigned in setup()

Page 33: Arduino Foundations

Scope: local

• If you only need to use a variable in a single function, you can declare it there, in which case its scope will be limited to that function

• For example:void setup(){ int pin = 13; pinMode(pin, OUTPUT); digitalWrite(pin, HIGH);}

Page 34: Arduino Foundations

Global vs. local scope

• Local scope can make it easier to figure out what happens to a variable

• If a variable is global, its value could be changed anywhere in the code, meaning that you need to understand the whole program to know what will happen to the variable

• For example, if your variable has a value you didn't expect, it can be much easier to figure out where the value came from if the variable has a limited scope

Page 35: Arduino Foundations

Functions

• Segmenting code into functions allows a programmer to create modular pieces of code that perform a defined task and then return to the area of code from which the function was "called”

• The typical case for creating a function is when one needs to perform the same action multiple times in a program

Page 36: Arduino Foundations

Advantages of code fragments in functions

• Functions help the programmer stay organised:– Often this helps to conceptualize the program

• Functions codify one action in one place so that the function only has to be thought out/debugged once:– This also reduces chances for errors in modification if the

code needs to be changed

• Functions make a sketch smaller/more compact because code sections are reused many times

• They make it easier to reuse code in other programs, and as a nice side effect, using functions also often makes the code more readable

Page 37: Arduino Foundations

Example: multiply function

• Function needs to be declared outside any other function, so "myMultiplyFunction()" can go either above or below the "loop()" area

Page 38: Arduino Foundations

Calling the example function

• To "call" our simple multiply function, we pass it parameters of the data-type that it is expecting:void loop{int i = 2;int j = 3;int k;

k = myMultiplyFunction(i, j); // k now contains 6}

Page 39: Arduino Foundations

Another example: average analog read

int ReadSens_and_Condition(){ int i; int sval = 0;

for (i = 0; i < 5; i++){ sval = sval + analogRead(0); // sensor on analog pin 0 }

sval = sval / 5; // average sval = sval / 4; // scale to 8 bits (0 - 255) sval = 255 - sval; // invert output return sval;}

Page 40: Arduino Foundations

Libraries

• Earlier on, we had the Morse code example• Can also convert its functions into a library• This allows other people to easily use the code

that you've written and to easily update it as you improve the library

Page 41: Arduino Foundations

What’s required?

• You need at least two files for a library:– Header file (with the extension .h)– Source file (with the extension .cpp)

• The header file has definitions for the library: basically a listing of everything that's inside; while the source file has the actual code

• More at:– http://arduino.cc/en/Hacking/LibraryTutorial

Page 42: Arduino Foundations

Morse.h#ifndef Morse_h#define Morse_h

#include "WProgram.h"

class Morse{ public: Morse(int pin); void dot(); void dash(); private: int _pin;};

#endif

Page 43: Arduino Foundations

Morse.cpp#include "WProgram.h"#include "Morse.h"

Morse::Morse(int pin){ pinMode(pin, OUTPUT); _pin = pin;}

void Morse::dot(){ digitalWrite(_pin, HIGH); delay(250); digitalWrite(_pin, LOW); delay(250); }

void Morse::dash(){ digitalWrite(_pin, HIGH); delay(1000); digitalWrite(_pin, LOW); delay(250);}