Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

54
Arduino Dov Kruger PhD © CIJE 2012, all rights reserved

Transcript of Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Page 1: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

ArduinoDov Kruger PhD

© CIJE 2012, all rights reserved

Page 2: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

What is Arduino?• Arduino is a wildly popular, open source

microcontroller• See the unit for details on– Open source software and hardware– Where to buy an Arduino– Where to get the software– How to install an Arduino on Windows• For MacOSX and Linux see the website

– The language reference manual

Page 3: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Programming an Arduino• Arduino is programmed in a language called Wiring• It is similar to C, C++, and Java• The full language will take some time to learn, but here are

a few vital facts– You need only a tiny subset of the language to achieve your goals

at first– You can learn incrementally

• Microcontroller programs tend to be– Simple (not enormous programs)– Highly repetitive (all control system programs are going to be

quite similar to each other)• Be Patient! In an hour, you will be amazed at what you can

do

Page 4: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

The Arduino UNO14 digital lines (0 to 13), each capable of either 5v output, or 5v input

Analog inputs A0-A5

USB cable allows programs to be downloaded and powers the board

Battery power can be plugged in here if you have the right size connector Power to supply to

off-board circuits

Page 5: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

The DFRobotics Romeo

This part is similar to an Arduino UNO

Same memory as an UNO (32Kb)

Power (up to 12V) for powering board and motors

Motor A

Motor B

Loads more interfaces to sensors

I2C serieal interfaces to other boards

Page 6: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Running the Arduino Software

• The Arduino Software is in

• P:\bin\Arduino-1.0• Pin it to the start menu if

you like for convenience• Click on the program to

run it

Page 7: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Select a Example: Blink

Page 8: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

The Code!/* Blink Turns on an LED on for one second, then off for one second, repeatedly. This example code is in the public domain. */

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

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}

Comment (doesn’t do anything)

Comment (doesn’t do anything)

Special procedures named setup (run once at the beginning) and loop (run over and over again, forever)

Page 9: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Comments Don’t matter/* Blink: Turns on an LED on for one second, then off for one second, repeatedly.*/

void setup(){ pinMode(13, OUTPUT); // ready to turn on the LED on output 13}

void loop() { digitalWrite(13, HIGH); // set the LED on (HIGH = 1) delay(1000); // wait for a second (delays are in milliseconds) digitalWrite(13, LOW); // set the LED off (LOW = 0) delay(1000); // wait for a second}

Page 10: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Run the ProgramThe Program is Downloaded… And starts running (look at the board)

Page 11: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Syntax Rules

• Only three major rules to handle most of the issues that can come up initially– Spaces don’t matter, except breaking up

predefined words• Example: void loop() is not the same as void lo op()• Example: x += 5; is not the same as x + = 5;

– Simple statements end in a semicolon– Blocks of code are surrounded by curly braces

Page 12: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Minimalist Program

void setup(){ }

void loop() {}

All programs must have a setup() and a loop()

This program does nothing

Page 13: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

What Happens if you Make a Mistake?

void lo op() {Blink:6: error: expected initializer before 'op'Blink.cpp: In function 'void setup()':Blink:11: error: expected `;' before '}' tokenBlink.cpp: At global scope:Blink:13: error: expected initializer before 'op'

Page 14: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Modify the Program

• Change the blink rate• Can you make three rapid blinks in a row?• Can you make an SOS? The pattern is made of

short blinks and long blinks:– Short short short

LONG LONG LONGshort short short

Page 15: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Writing new Functions• The more complicated the blink pattern, the

longer the program• You can reduce the work by putting repeated

patterns in a function• What do you think goes in these functions?void dit()

{ }

void dah(){

}

Page 16: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

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

void dit() { digitalWrite(13, HIGH); // set the LED on delay(100); digitalWrite(13, LOW); // set the LED off delay(100);}void dah() { digitalWrite(13, HIGH); // set the LED on delay(300); digitalWrite(13, LOW); // set the LED off delay(100); }void loop() { dit(); dit(); dit(); delay(500); dah(); dah(); dah(); delay(500); dit(); dit(); dit(); delay(500);}

Page 17: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Blinking an External LED

• Blinking an External LED is almost as easy as the internal one– But you have to build a circuit

• The Arduino is powered off the USB port (+5v)– So high will be +5v– Since your LED will burn out if you put 5v across it,

you will need a resistor– Can you compute what resistor, given that the

current should be 30mA? R = V/I

Page 18: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

BreadBoardPowered totally by ArduinoLimited power available (high intensity LED wouldn’t light!)

Page 19: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Multi-LED Program

• Set Multiple pins to output mode• Turn on and off as desired

Page 20: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

/* ExternalLED: Turns on internal LED for .2 sec, then external for .2 sec */

void setup() { pinMode(13, OUTPUT); pinMode(7, OUTPUT); }

const int onDelay = 200, offDelay = 500;

void loop() { digitalWrite(13, HIGH); // set the LED on delay(onDelay); digitalWrite(13, LOW); // set the LED off delay(offDelay); digitalWrite(7, HIGH); // set the LED on delay(onDelay); digitalWrite(7, LOW); // set the LED off delay(offDelay);}

Page 21: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

/* ExternalLED: Turns on internal LED for .2 sec, then external for .2 sec */

void setup() { pinMode(13, OUTPUT); pinMode(7, OUTPUT); }

const int onDelay = 200, offDelay = 500;

// turn on whichever digital port is passed in as an argumentvoid turnOneOn(int which) { digitalWrite(which, HIGH); // set the LED on delay(onDelay); digitalWrite(which, LOW); // set the LED off delay(offDelay);}

void loop() { turnOneOn(13); turnOneOn(7);}

Page 22: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Digital Input Circuits

• To read a button or switch– A digital pin must connect to HIGH or LOW when

the button is pressed– It should connect to the opposite when the button

is not pressed.– This is the circuit:

Page 23: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Reading in a Button

• Buttons are digital inputs– Either on (5v) or off (0v)

• To use a button, place a button on the breadboard– Cut two wires long enough to reach from the Arduino to

the breadboard– DO NOT OVERLAP THE ALUMINUM of the breadboard with

the Arduino, you could short it out.– THE ARDUINO MUST ALWAYS BE ON A NON-CONDUCTIVE

SURFACE– (Anyone care to design an enclosure to protect our little

computers?)

Page 24: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Reading in a Button, contd

• Connect one side of the button to 5v on the Arduino

• Connect the other side of the button to one of the digital input/outputs (I used pin 7)

• In setup, you must set pin 7 to input mode• In loop, you can repeatedly test the pin with

the digitalRead command• The digitalRead command returns true or false

Page 25: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

The Code/* Listen for a button press on pin 7 and when pressed, print out PRESSED and wait for 0.1 seconds Author: Dov Kruger Feb 1, 2012*/void setup() { // initialize the digital pin as an output. // Pin 13 has an LED connected on most Arduino boards: pinMode(7, INPUT); Serial.begin(9600);}void loop() { if (digitalRead(7)) { // everything within {} is execute ONLY IF Serial.println("pressed!"); // the button is pressed! } delay(100); // wait for a second }

Page 26: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Reading in an Analog Signal

• With computers, the input is always voltage– The trick is to convert whatever the signal is into

voltage– The simplest technique is a voltage divider

• Pick a resistor as close to the value of the resistance of the sensor as possible

• Voltage across either should be ½ of total

Page 27: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Code to Read an Analog Signal/* AnalogReadSerial Reads an analog input on pin 0, prints the result to the serial monitor */

void setup() { Serial.begin(9600);}

void loop() { int sensorValue = analogRead(A0); Serial.println(sensorValue, DEC);}

Page 28: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Summary• The Arduino has a lot of advantages– Inexpensive– Fast development cycle (quick and easy to use)– Fairly high computing power– Small package, can fit in portable products– Large memory, and larger with other versions– A huge base of users and accessory products– A learning curve that is reasonably good

• One disadvantage– Arduino outputs are not protected– High voltage will kill the board

Page 29: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Arduino 2: Programming Constructs and Variables

• By the end of this unit, you will be able to:– List the different data types in Wiring and the kinds of

data they hold– Identify the data types– Write programs using loops and if statements to

execute more complicated algorithms

– Perform linear interpolation– Perform quadratic interpolation– Compute a weighted average

Page 30: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Too Many Repeated Constants

• Putting many repeated constants in a program leads to errors– Someone could mistype one

• Difficult to maintain because– Replacing every 100 in the program might not be

desired, but we might want to change every short delay for the dit() and make it a little longer

• You can define constants so that changing one value in one place changes all references

Page 31: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

const int ditDelay = 100, dahDelay = 300;const int wordDelay = 500;const int charDelay = 100;

void dit() { digitalWrite(13, HIGH); // set the LED on delay(ditDelay); // “short” digitalWrite(13, LOW); // set the LED off delay(charDelay); // gap between}void dah() { digitalWrite(13, HIGH); // set the LED on delay(dahDelay); // wait for a “long” digitalWrite(13, LOW); // set the LED off delay(charDelay); // gap delay }

With ConstantsHow would you change the speed of this morse code if you wanted to make it faster?

Page 32: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

void s(){ dit(); dit(); dit(); delay(charDelay); }

void o(){ dah(); dah(); dah(); delay(charDelay);}

void loop() { s(); o(); s(); delay(charDelay);}

The Main Loop

Page 33: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Variables and Counting

Variables let a program compute values and store results

There are a number of data typesThe type int is a whole numberint x = 50;int y = x + 50; // y is now 100int z = y * 2; // z is now 200

Page 34: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Data Types in Wiringvoid The untype, means “nothing”boolean True/falsechar A single character, one byte, -128..127unsigned char 0..255byte 0..255int A 16 bit integer: -32768..32767unsigned int A 16 bit positive only: 0..65535word Synonym for unsigned intlong 32-bit int -2.1 billion..2.1 billionunsigned long 0..2^32-1 (about 4 billion)float Decimal number, 7 digits precisiondouble Alias for float (same thing in Wiring)string A sequence of charactersString A sequence of characters

Page 35: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Focus On Numbers• Most of the time, microcontrollers are

computing with numbers– You don’t go writing word processors on a

computer with no screen!– It’s all about

reading in,computingsome number,and taking anaction

Type Description Range of Valueschar A single character,

one byte-128..127

unsigned char

A single byte without negative numbers

0..255

int A 16 bit integer 32768..32767unsigned int

A 16 bit positive only

0..65535

long 32-bit int -2.1B ... +2.1Bunsigned long

0..2^32-1 (about 4 billion)

0 …4294967295

Page 36: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Integral Types

• In math, integers are infinite

• On a computer, integer types have a finite size because they are stored as bits– (on = 1, off = 0)

• The table shows a hypothetical 3-bit integer and what the numbers would be signed and unsigned

Binary Unsigned integer

Signed integer

000 0 0

001 1 1

010 2 2

011 3 3

100 4 -4

101 5 -3

110 6 -2

111 7 -1

Unsigned: 7 + 1 0Signed: -1 + 1 0

Page 37: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Behavior of Integral Types

• When arithmetic results in a value too big, it just “wraps around”

• Example:– The following code is an infinite loop, because x can never get to 1000

(a byte holds a maximum of 255)– Each time x gets to 255, adding 1 bring it back to 0

char x = 0;while (x < 1000) { Serial.println(x); x++;}

Page 38: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Behavior of Integral Types, contd

• Operations on integral types are always whole numbers.

• 3 + 4 7• 3 * 4 12• 3 / 2 1 (not 1.5, fraction discarded)• Integer remainder: 3 % 2 1, 4 % 2 0• Overflows can surprise you:

for int: 512 * 512 -something (try it!)

Page 39: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Variable Rate Blinking/* Chirp: Turn an LED on for .1 sec, then .2, then .3, etc.*/

void loop() { int delayTime = 100; while (true) { digitalWrite(13, HIGH); // set the LED on delay(delayTime); digitalWrite(13, LOW); // set the LED off delay(delayTime); delayTime += 100; }}

Page 40: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Displaying To the PC Screen

• In order to tell what is happening on the Arduino, it is very helpful to display values across the cable to the computer– The Arduino Doesn’t have a screen!

void setup() { Serial.begin(9600);}

void loop() { Serial.println(“Hello!”); delay(1000);}

Set the speed to talk to the console window

Keep printing “Hello”

Page 41: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Meanwhile, in the IDE…

Page 42: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Counting Loops

• In order to execute a loop a finite number of times:– Use the while statement– Or the equivalent but more compact for statement

int x = 0;while (x < 10) { // whatever you want x = x + 1;}

for (int x = 0; x < 10; x++) { // whatever you want}

Executed once the first time

Executed before the loop each time

Executed after the loop each time

Page 43: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Demonstrating a loop without blinking: Print

• The Serial object connects across the serial line to another computer or device

• In this program, you will use it to print back to the computer you are programming from (your laptop)

• In order to use the serial device, you must initialize its speed– The other side – the pc – must agree with that speed– The two sides establish communication– You can view the output by clicking the serial monitor button on the

top right of the Arduino window• System.println prints and then adds a newline (goes to a new

line)• System.print just prints

Page 44: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Printing to your laptop

void setup() { Serial.begin(9600);}

void loop() { for (int i = 0; i < 10; i++) { Serial.println(i, DEC); }}

Page 45: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.
Page 46: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Case Study: Sum the Numbersvoid loop(){ const int n = 100; unsigned long sum = 0; for (int i = 1; i < n; i++) sum += i; Serial.println(sum);}

Page 47: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Brute Force vs. Intelligence// Algorithm due to Karl Friedrich Gauss (at age 10)// This is 100 times faster than the previous one! And no matter how big the number, this algorithm computes it instantly.

void loop(){ int n = 100; unsigned long sum = n * (n+1) / 2; Serial.println(sum);}

Page 48: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Computing Numbers in a Loop

• Definition of prime numbers: n > 1 with only two factors: 1, n

• Examples of primes: 2, 3, 5, 7, 11• How do you compute primes?• Many ways, showing increasing complexity as

a tradeoff for efficiency• First way: Brute force. Test n for divisibility by

every number less than n

Page 49: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Brute Force Prime Numbersvoid loop(){ for (int n = 2; n < 100000; n++) { for (int m = 2; m < n; m++) { if (n % m == 0) { //evenly divisible (not prime) goto notPrime; } } Serial.print(n); notPrime: ; }}

Page 50: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Better Algorithm

• Arduino is a slow little computer– Great opportunity to show the difference between

efficient and inefficient code– Better algorithm: Don’t divide by numbers greater than

n• Example: 17• 17 % 2 != 0 (17 is not even)• 17 % 3 != 0 (17 is not a multiple of 3)• 17 % 4 != 0 (17 is not a multiple of 4)• 17 % 5 is unnecessary

Page 51: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Faster Test

void loop(){ for (int n = 2; n < 100000; n++) for (int m = 2; m < sqrt(n); m++) { if (n % m == 0) { //evenly divisible (not prime) goto notPrime; } } Serial.print(n);notPrime: ;}

Page 52: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Much Faster: Skip the Tests Where Possible

void loop(){ Serial.print(2); // special case, don’t test any other even number. Serial.print(“ “); for (int n = 3; n < 100000; n += 2) { int m; for (m = 3; m < n; m+= 2) { if (n % m == 0) { //evenly divisible (not prime) break; } } if (m >= n) { Serial.print(n); Serial.print(“ “); } }}

Page 53: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Much Better Tests Exist

• There are far better algorithms ranging upwards in complexity.

• If you are curious, check out: Eratosthenes Sieve (thousands of years old).

• Think about skipping even more values. Can you come up with a way?

• Fermat’s “Little Theorem” and Miller tests offer a completely new way.

Page 54: Arduino Dov Kruger PhD © CIJE 2012, all rights reserved.

Summary: Computing Improves over Time

• Over time, hardware has improved by orders of magnitude– Computing power has increased by a factor of 2

every 9-18 months until recently• “Moore’s Law”• More than a factor of 1,000,000,000 over three decades

– Algorithms have also gotten enormously better• The combination of computers and algorithms

makes computing so much faster today