Arduino - drsphysics.com

Download Report

Transcript Arduino - drsphysics.com

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
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
The Arduino UNO
14 digital lines (0 to 13), each
capable of either 5v output, or
5v input
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
Analog inputs A0-A5
The DFRobotics Romeo
Same memory
as an UNO
(32Kb)
This part is
similar to an
Arduino UNO
Loads more interfaces to sensors
Motor A
Motor B
Power (up to
12V) for
powering board
and motors
I2C serieal
interfaces to
other boards
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
Select a Example: Blink
The Code!
Comment
(doesn’t do
anything)
/*
Blink
Turns on an LED on for one second, then off for one second, repeated
This example code is in the public domain.
*/
Comment
(doesn’t do
anything)
Special
procedures
named setup
(run once at
the beginning)
and loop (run
over and over
again, forever)
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
}
Comments Don’t matter
/*
Blink: Turns on an LED on for one second, then off for one second,
repeatedly.
*/
void setup()
{
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
// ready to turn on the LED on output 13
// set the LED on (HIGH = 1)
// wait for a second (delays are in milliseconds)
// set the LED off (LOW = 0)
// wait for a second
Run the Program
The Program is Downloaded
… And starts running (look at the board)
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
Minimalist Program
All programs must have a setup() and
a loop()
This program does nothing
void setup()
{
}
void loop() {
}
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 '}' token
Blink.cpp: At global scope:
Blink:13: error: expected initializer before 'op'
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 LONG
short short short
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()
{
}
void setup() {
pinMode(13, OUTPUT);
}
void dit() {
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
}
void dah() {
digitalWrite(13, HIGH);
delay(300);
digitalWrite(13, LOW);
delay(100);
}
void loop() {
dit(); dit(); dit();
delay(500);
dah(); dah(); dah();
delay(500);
dit(); dit(); dit();
delay(500);
}
// set the LED on
// set the LED off
// set the LED on
// set the LED off
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
BreadBoard
Powered totally by Arduino
Limited power available (high intensity
LED wouldn’t light!)
Multi-LED Program
• Set Multiple pins to output mode
• Turn on and off as desired
/*
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);
}
/*
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 argument
void 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);
}
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:
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?)
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
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
}
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
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);
}
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
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
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
With Constants
How would you
change the speed const int ditDelay = 100, dahDelay = 300;
of this morse code const int wordDelay = 500;
if you wanted to
const int charDelay = 100;
make it faster?
void dit() {
digitalWrite(13, HIGH);
delay(ditDelay);
digitalWrite(13, LOW);
delay(charDelay);
}
void dah() {
digitalWrite(13, HIGH);
delay(dahDelay);
digitalWrite(13, LOW);
delay(charDelay);
}
// set the LED on
// “short”
// set the LED off
// gap between
// set the LED on
// wait for a “long”
// set the LED off
// gap delay
The Main Loop
void s()
{
dit(); dit(); dit();
delay(charDelay);
}
void o()
{
dah(); dah(); dah();
delay(charDelay);
}
void loop() {
s(); o(); s();
delay(charDelay);
}
Variables and Counting
Variables let a program compute values and
store results
There are a number of data types
The type int is a whole number
int x = 50;
int y = x + 50; // y is now 100
int z = y * 2; // z is now 200
Data Types in Wiring
void
The untype, means “nothing”
boolean
True/false
char
A single character, one byte, -128..127
unsigned char
0..255
byte
0..255
int
A 16 bit integer: -32768..32767
unsigned int
A 16 bit positive only: 0..65535
word
Synonym for unsigned int
long
32-bit int -2.1 billion..2.1 billion
unsigned long
0..2^32-1 (about 4 billion)
float
Decimal number, 7 digits precision
double
Alias for float (same thing in Wiring)
string
A sequence of characters
String
A sequence of characters
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!
Type
Description
Range of Values
– It’s all about
char
A single character,
-128..127
reading in,
one byte
computing
unsigned
A single byte
0..255
some number,
char
without negative
numbers
and taking an
int
A 16 bit integer
32768..32767
action
unsigned
int
A 16 bit positive
only
0..65535
long
32-bit int
-2.1B ... +2.1B
unsigned
long
0..2^32-1 (about 4
billion)
0 …4294967295
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  0
Signed: -1 + 1  0
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++;
}
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!)
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;
}
}
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”
Meanwhile, in the IDE…
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
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
Printing to your laptop
void setup() {
Serial.begin(9600);
}
void loop() {
for (int i = 0; i < 10; i++) {
Serial.println(i, DEC);
}
}
Case Study: Sum the Numbers
void loop()
{
const int n = 100;
unsigned long sum = 0;
for (int i = 1; i < n; i++)
sum += i;
Serial.println(sum);
}
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);
}
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
Brute Force Prime Numbers
void 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: ;
}
}
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
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: ;
}
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(“ “);
}
}
}
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.
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