Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

Arduino - Controllers

Uploaded by

Senthil Ganesh R
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Arduino - Controllers

Uploaded by

Senthil Ganesh R
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 158

Arduino - Controllers

Real time- Concept Map


ME 106
User ME 120

Interface
Power
Source

Controller
(Hardware & Software)
Power
Interface

INTEGRATION Signal
Conditioning
Actuator

Sensor

System to
Control
ANALOG
INPUTS
What is the Arduino

todbot.com/blog/bionicarduino
What is a Development Board
• A printed circuit
board designed to
facilitate work with a
particular
microcontroller.
• Typical components include:
• power circuit
• programming interface
• basic input; usually buttons and LEDs
• I/O pins
The Arduino Development Board

Making-robots-with-arduino.pdf
The Arduino Microcontroller: Atmel
ARV Atmega 328
Getting Started
• Check out: http://arduino.cc/en/Guide/HomePage
1. Download & install the Arduino environment (IDE)
2. Connect the board to your computer via the UBS cable
3. If needed, install the drivers (not needed in lab)
4. Launch the Arduino IDE
5. Select your board
6. Select your serial port
7. Open the blink example
8. Upload the program
Arduino Hardware
http://www.arduino.cc/en/Main/ArduinoBoardDuemilanove
See the handout:
Arduino_ATmega328_pin_mapping_and_schematic
Pin 13 LED
Digital pins header
USB
connector Reset button

ATmega328 MCU

Barrel jack Analog pins header

Power-ground header
Try It: Connect the USB Cable

todbot.com/blog/bionicarduino
Arduino IDE

See: http://arduino.cc/en/Guide/Environment for more information


Select Serial Port and Board
Status Messages

todbot.com/blog/bionicarduino
todbot.com/blog/bionicarduino
Structure of an Arduino Program
/* Blink - turns on an LED for DELAY_ON msec,
then off for DELAY_OFF msec, and repeats
• An arduino program == ‘sketch’ BJ Furman rev. 1.1 Last rev: 22JAN2011
*/
– Must have: #define LED_PIN 13 // LED on digital pin 13
• setup() #define DELAY_ON 1000
#define DELAY_OFF 1000
• loop()
– setup() void setup()
{
• configures pin modes and // initialize the digital pin as an output:
registers pinMode(LED_PIN, OUTPUT);
}
– loop()
// loop() method runs forever,
• runs the main body of the // as long as the Arduino has power
program forever
– like while(1) {…} void loop()
{
– Where is main() ? digitalWrite(LED_PIN, HIGH); // set the LED on
delay(DELAY_ON); // wait for DELAY_ON msec
• Arduino simplifies things
digitalWrite(LED_PIN, LOW); // set the LED off
• Does things for you delay(DELAY_OFF); // wait for DELAY_OFF msec
}
Example 1
 Make Arduino pins 3, 5, and 7 (PD3, PD5, and
PD7) to be outputs
• Arduino approach • Alternate approach
pinMode(3, OUTPUT); DDRD = 0b10101000;
pinMode(5, OUTPUT);
pinMode(7, OUTPUT); or
Or if me106.h is used:
DDRD = 0xA8;
pinMode(PIN_D3, OUTPUT);
pinMode(PIN_D5, OUTPUT); or
pinMode(PIN_D7, OUTPUT);
DDRD | = 1<<PD7 | 1<<PD5 | 1<<PD3;

More on this coming soon!


Example 2
 Make pins Arduino pins 0 and 1 (PD0 and PD1)
inputs, and turn on pull-up resistors
• Arduino approach • Alternate approach
pinMode(0, INPUT); DDRD = 0; // all PORTD pins inputs
pinMode(1, INPUT); PORTD = 0b00000011;
digitalWrite(0, HIGH); or
digitalWrite(1, HIGH); PORTD = 0x03;
Or if me106.h is used:
or better yet:
pinMode(PIN_D0, INPUT); DDRD & = ~(1<<PD1 | 1<<PD0);
pinMode(PIN_D1, INPUT); PORTD | = (1<<PD1 | 1<<PD0);
digitalWrite(PIN_D0, HIGH);
digitalWrite(PIN_D1, HIGH); More on this coming soon!
Reading/writing digital values
• digitalWrite(13, LOW); // Makes the output
voltage on pin 13 , 0V

• digitalWrite(13, HIGH); // Makes the output


voltage on pin 13 , 5V

• int buttonState = digitalRead(2); // reads the


value of pin 2 in buttonState
Reading/Writing Analog Values
• analogRead(A0); // used to read the analog
value from the pin A0

• analogWrite(2,128);
Important functions
• Serial.println(value);
– Prints the value to the Serial Monitor on your computer
• pinMode(pin, mode);
– Configures a digital pin to read (input) or write (output) a
digital value
• digitalRead(pin);
– Reads a digital value (HIGH or LOW) on a pin set for input
• digitalWrite(pin, value);
– Writes the digital value (HIGH or LOW) to a pin set for
output
DELAY (2/3)
• Arduino example:
delay(int milliseconds)
//creates a delay in ms
delayMicroseconds(int microseconds)
//creates a delay in μs

delay(1000); //one second delay


delayMicroseconds(10); //10 μs delay
Setting the Pin Data Direction
• Microcontrollers are fundamentally digital
devices. For digital IO pins:
– Information is ‘coded’ in two discrete states:
• HIGH or LOW (logic: 1 or 0)
• Voltages
– TTL
» 5 V (for HIGH)
» 0 V (for LOW)
– 3.3 V CMOS
» 3.3 V (for HIGH)
» 0 V (for LOW)

• Arduino
– pinMode(pin_no., dir)
• Ex. Make Arduino pin 3 (PD3) an output
– pinMode(3, OUTPUT);
– pinMode(PIN_D3, OUTPUT); // with me106.
Port Pin Data Directionality
• Input
– When you want to take information from the external
world (sensors) into the MCU
• Output
– When you want to change the state of something outside
the MCU (turn a motor on or off, etc.)
• Pins default to input direction on power-up or reset
• Your program can set or change the directionality of
a pin at any time
Add an External LED to pin 13

• File > Examples > Digital > Blink


• LED’s have polarity
– Negative indicated by flat side of the housing
and a short leg

www.instructables.com
A Little Bit About Programming
• Code is case
sensitive
• Statements are
commands and
must end with a
semi-colon
• Comments follow
a // or begin with /*
and end with */
• loop and setup
Our First Program
Terminology
Digital I/0

pinMode(pin, mode)
Sets pin to either INPUT or OUTPUT
digitalRead(pin)
Reads HIGH or LOW from a pin
digitalWrite(pin, value)
Writes HIGH or LOW to a pin
Electronic stuff
Output pins can provide 40 mA of current
Writing HIGH to an input pin installs a 20KΩ pullup
Arduino Timing

• delay(ms)
– Pauses for a few milliseconds
• delayMicroseconds(us)
– Pauses for a few microseconds
• More commands:
arduino.cc/en/Reference/HomePage
Digital? Analog?
• Digital has two values: on and off
• Analog has many (infinite) values
• Computers don’t really do analog, they quantize
• Remember the 6 analog input pins---here’s how
they work

todbot.com/blog/bionicarduino
Converting Analog Value to Digital
Bits and Bytes
Variables

www3.ntu.edu.sg
Putting It Together
• Complete the sketch
(program) below.
• What output will be
generated by this program?
• What if the schematic were
changed? 
Pin Used as an Output
• Turn on an LED, which is connected
ATmega328
to pin Arduino pin 0 (PD0) (note the
resistor!)
Arduino
pin 0
(PD0)
– Turn on the LED

• digitalWrite(PIN_LED,HIGH);
– Turn off the LED

• digitalWrite(PIN_LED,LOW);
Pins as Inputs and Pull-up Resistors - 1
• Using a switch as a sensor
ATmega328
– Ex. Seat belt sensor
– Detect the switch state Arduino
pin 3
(PD3)

SPST

momentary
Pins as Inputs and Pull-up Resistors - 2
• Switch as a sensor, cont.
ATmega328
– Make the voltage on the pin
VTG= +5V
determinate by turning on the pull-up
resistor for PD3
1
• Assuming PD3 is an input: PD3
– digitalWrite(PIN_SWITCH,HIGH); 0
turns on the “pull-up” resistor

– pinMode(PIN_SWITCH,INPUT_PULLUP);
Pins as Inputs and Pull-up Resistors - 3
• Switch as a sensor, cont.
ATmega328
– To turn off the pull-up resistor VTG= +5V
• Assuming PD3 is an input:
digitalWrite(PIN_SWITCH,LOW); 1
turns the “pull-up” resistor off PD3
0
Pins as Inputs and Pull-up Resistors - 4
• Possibility of ‘weak drive’
ATmega328
when pull-up resistor is VTG= +5V
turned on iweak
– Pin set as an input with a pull- 1
PD3
up resistor turned on can 0

source a small current


• Remember this!
Digital IO – Practice 1
• ‘Reading a pin’
ATmega328
– Write some lines of C code for the
Arduino to determine a course of
action if the seat belt has been latched
(switch closed). PD3
• If latched, the ignition should be enabled
through a call to a function ig_enable().
• If not latched, the ignition should be
disabled through a call to a function
ig_disable()
– Write pseudocode first
Digital IO – Practice 1 Pseudocode
• ‘Reading a pin’
• Pseudocode: ATmega328
Set up PD3 as an input VTG= +5V
Turn on PD3 pull-up resistor
Read voltage on Arduino pin 3 (PIN_D3)
1
IF PIN_D3 voltage is LOW (latched), THEN PD3
call function ig_enable() 0
ELSE
call function ig_disable()
Digital IO – Practice 1 Code
• ‘Reading a pin’ ATmega328

• Pseudocode: VTG= +5V

Set up PD3 as an input


Turn on PD3 pull-up resistor 1
Read voltage on Arduino pin 3 (PIN_D3) PD3
IF PIN_D3 voltage is LOW (latched), THEN 0

call function ig_enable()


ELSE
call function ig_disable()

One way  #define PIN_SWITCH 3


(snippet, not full program) #define LATCHED LOW
pinMode(PIN_SWITCH,INPUT_PULLUP);
belt_state = digitalRead(PIN_SWITCH);
if (belt_state == LATCHED)
{ ig_enable(); }
else
{ ig_disabled(); }
Digital IO – Practice 2
• ‘Reading from and writing to a ATmega328
pin’ PD3

– Write some lines of C code for the PD2


Arduino to turn on a lamp (PD2) and
buzzer (PD3) if the key is in the
ignition (PD0 closed), but seat belt is
not latched (PD1 open) PD0, PD1
• (diagram shows only one of the two
switches, but both are similar)
– Pseudocode first
Digital IO – Practice 2 Pseudocode
• Pseudocode:
Set up data direction of pins ATmega328
Make PD0 and PD1 inputs
Turn on pull up resistors for PD0 and PD1
PD3
Make PD2 and PD3 outputs
Loop forever PD2
IF key is in ignition THEN
IF belt is latched, THEN
Turn off buzzer VTG= +5V
Turn off lamp
ELSE
Turn on lamp
Turn on buzzer 1
ELSE PD0, PD1
Turn off buzzer
Turn off lamp 0
Digital IO – Practice 2 (Arduino style
code)
#define PIN_IGNITION 0
#define PIN_SEATBELT 1
#define PIN_LED 2 ATmega328
#define PIN_BUZZER 3
#define SEATBELT_LATCHED LOW
PD3
#define KEY_IN_IGNITION LOW
#define LED_ON HIGH PD2
#define LED_OFF LOW
#define BUZZER_ON HIGH VTG= +5V
#define BUZZER_OFF LOW
void setup()
{
pinMode(PIN_IGNITION, INPUT_PULLUP); // key switch 1
PD0, PD1
pinMode(PIN_SEATBELT, INPUT_PULLUP); // belt latch switch
pinMode(PIN_LED, OUTPUT); // lamp 0
pinMode(PIN_BUZZER, OUTPUT); // buzzer
}
void loop()
{ /* see next page for code */}
Digital IO – Practice 2 (Arduino style
code)
/* see previous page for code before loop() */
void loop()
{ ATmega328
int key_state = digitalRead(PIN_IGNITION);
int belt_state = digitalRead(PIN_SEATBELT);
PD3
if (key_state == KEY_IN_IGNITION)
{ PD2
if (belt_state == SEATBELT_LATCHED)
{ VTG= +5V
digitalWrite(PIN_BUZZER, BUZZER_OFF);
digitalWrite(PIN_LED, LED_OFF);
}
else // key is in ignition, but seatbelt NOT latched 1
PD0, PD1
{
digitalWrite(PIN_BUZZER, BUZZER_ON); 0
digitalWrite(PIN_LED, LED_ON);
}
else // key is NOT in ignition
{
digitalWrite(PIN_BUZZER, BUZZER_OFF);
digitalWrite(PIN_LED, LED_OFF);
}
}
}
Digital IO – Practice 3 (Register style
code)
/* NOTE: #defines use predefined PORT pin numbers for ATmega328 */
#define PIN_IGNITION PD0 ATmega328
#define PIN_SEATBELT PD1
PD3
#define PIN_LED PD2
#define PIN_BUZZER PD3
#define SEATBELT_LATCHED LOW
PD2
#define KEY_IN_IGNITION LOW
#define LED_ON HIGH VTG= +5V
#define LED_OFF LOW
#define BUZZER_ON HIGH
1
#define BUZZER_OFF LOW PD0, PD1
#define _BIT_MASK( bit ) ( 1 << (bit) ) // same as _BV( bit)
0
void setup()
{
PORTD = 0; // all PORTD pullups off
DDRD = _BIT_MASK(PIN_LED) | _BIT_MASK(PIN_BUZZER); // LED and buzzer
PORTD | = _BV(PIN_IGNITION) | _BV(PIN_SEATBELT); // pullups for switches
}

/* See next page for loop() code */


Digital IO – Practice 3 (Register style
code)
/* see previous page for setup() code */
void loop()
{ ATmega328
uint8_t current_PORTD_state, key_state, belt_state;
current_PORTD_state = PIND; // snapshot of PORTD pins
PD3
key_state = current_PORTD_state & _BV(PIN_IGNITION);
belt_state = current_PORTD_state & _BV(PIN_SEATBELT); PD2
if (key_state == KEY_IN_IGNITION)
{ VTG= +5V
if (belt_state == SEATBELT_LATCHED)
{
PORTD & = ~( _BV(PIN_LED) | _BV(PIN_BUZZER) ); 1
}
PD0, PD1
else 0
{
PORTD | = ( _BV(PIN_LED) | _BV(PIN_BUZZER) );
}
}
else
{
PORTD & = ~( _BV(PIN_LED) | _BV(PIN_BUZZER) );
}
}
Fading of LED
• 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
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, 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);
}
Traffic Light
Simple traffic Light Program
// variables
int GREEN = 2; int YELLOW = 3;
int RED = 4;
int DELAY_GREEN = 5000;
int DELAY_YELLOW = 2000;
int DELAY_RED = 5000;
// basic functions
void setup()
{
pinMode(GREEN, OUTPUT);
pinMode(YELLOW, OUTPUT);
pinMode(RED, OUTPUT);
}
void loop()
{
green_light();
delay(DELAY_GREEN);
yellow_light();
delay(DELAY_YELLOW);
red_light(); delay(DELAY_RED);
}
void green_light()
{
digitalWrite(GREEN, HIGH);
digitalWrite(YELLOW, LOW);
digitalWrite(RED, LOW);
}
void yellow_light()
{
digitalWrite(GREEN, LOW); digitalWrite(YELLOW, HIGH);
digitalWrite(RED, LOW);
}
void red_light()
{
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW); digitalWrite(RED, HIGH);
}
LCD Display
LCD library code
• Create a new LiquidCrystal object:
LiquidCrystal lcd(p1,p2,p3,p4,p5,p6);

Type of object Name of the new object Data passed to the object constructor

• When a new object is created, the data


passed to the constructor is stored in the
object. Thus, whenever we use the variable
lcd again in the program, the lcd object
“knows” that it is connected to p1, p2, ..., p6.

64
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup()
Parameters: (rs, enable, d4, d5, d6, d7)
{
lcd.begin(16, 2);
lcd.print("hello, world!");
}
void loop()
{
lcd.setCursor(0, 1);
lcd.print(millis() / 1000);
}
void loop() {
#include <LiquidCrystal.h> lcd.print("Arduino"); // Prints "Arduino" on
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); the LCD
delay(3000); // 3 seconds delay
// Creates an LC object. Parameters: (rs, lcd.setCursor(2,1); // Sets the location at
enable, d4, d5, d6, d7) // which subsequent text written to the LCD
will be displayed
void setup() lcd.print("LCD Tutorial");
{ delay(3000);
lcd.begin(16,2); lcd.clear(); // Clears the display
lcd.blink(); //Displays the blinking LCD
} cursor
delay(4000);
lcd.setCursor(7,1);
// Initializes the interface to the LCD delay(3000);
screen, and specifies the dimensions lcd.noBlink(); // Turns off the blinking LCD
(width and height) of the display cursor
lcd.cursor(); // Displays an underscore (line)
at the position to which the next character
will be written
delay(4000);
lcd.noCursor(); // Hides the LCD cursor
lcd.clear(); // Clears the LCD screen
}
Character matrix on a 4 X 20 display
• Row and column indices begin with zero

67
7 Segment Display
void setup()
{
pinMode(2,OUTPUT); pinMode(3,OUTPUT); pinMode(4,OUTPUT);
pinMode(5,OUTPUT); pinMode(6,OUTPUT); pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
}
void loop()
{
for(int i=2;i<9;i++)
{
digitalWrite(i,HIGH);
delay(600);
}
for(int i=2;i<9;i++)
{
digitalWrite(i,LOW);
delay(600);
} delay(1000);
}
ADC Example
// These constants won't change. They're void loop() {
used to give names to the pins used: // read the analog in value:
sensorValue = analogRead(analogInPin);
const int analogInPin = A0;
// Analog input pin that the potentiometer // map it to the range of the analog out:
is attached to
const int analogOutPin = 9;
outputValue = map(sensorValue, 0, 1023, 0, 25
// Analog output pin that the LED is 5);
attached to
// change the analog out value:
int sensorValue = 0; analogWrite(analogOutPin, outputValue);
// value read from the pot
int outputValue = 0; // print the results to the serial monitor:
// value output to the PWM (analog out) Serial.print("sensor = " );
Serial.print(sensorValue);
void setup() { Serial.print("\t output = ");
// initialize serial communications at 9600 Serial.println(outputValue);
bps:
Serial.begin(9600); // wait 2 milliseconds before the next loop
} // for the analog-to-digital converter to settle
// after the last reading:
delay(2);}
INTERNET OF THINGS WITH
ARDUINO
Arduino with GPS (1/4)
• Three modes:
– Stand-alone: GPS obtains information such as position and altitude
with only the signal of the satellites
• slowest of the three modes
• AT+CGPSINFO command brings directly latitude, logtitude, date,
UTC time, altitude and speed
– S-GPS: module connects to a GPS server
• module calculates the position
– A-GPS: Three modes
• MS-Assisted: Server sends data and calculates position
• MS-based: Server sends aiding data, module calculates position
• Stand-Alone: Module demodulates GPS data and calculates
position
Arduino with GPS (2/4)
• AT+CGPSINFO returns the GPS info in a string:
• [<latitude>],[<N/S>],[<longitude>],[<E/W>],[<date>],
[<UTC_time>],[<altitude>],[<speedOG>],[<course>]
Arduino with GPS (3/4)
int8_t answer;
int onModulePin= 2;
char gps_data[100]; //will perform 100 GPS data reads
int counter;
void setup(){
pinMode(onModulePin, OUTPUT);
Serial.begin(115200);
Serial.println("Starting...");
power_on();
delay(5000); // starts GPS session in stand alone mode
}
}
void power_on(){ //void power_on() should be placed AFTER void loop(), used here for lecture
digitalWrite(onModulePin,HIGH); //GPS module requires a 3 sec pulse on onModulePin
delay(3000);
digitalWrite(onModulePin,LOW);
}
Arduino with GPS (4/4)
void loop(){
answer = sendATcommand("AT+CGPSINFO","+CGPSINFO:",1000);
// request info from GPS
if (answer == 1) {
counter = 0;
do{
while(Serial.available() == 0); //reading GPS data
gps_data[counter] = Serial.read();
counter++;
}
}
Serial.print("GPS data:"); //printing GPS data
Serial.print(gps_data);
}
Connecting through 3G (1/2)
int8_t answer;
int onModulePin = 2, aux;
char aux_str[50];
void setup(){
pinMode(onModulePin, OUTPUT);
Serial.begin(115200);
Serial.println("Starting...");
power_on();
delay(3000); //sets the PIN code
sprintf(aux_str, "AT+CPIN=%s", pin_number);
sendATcommand(aux_str, "OK", 2000);
delay(3000);
Connecting through 3G (2/2)
while( (sendATcommand("AT+CREG?", "+CREG: 0,1", 500) ||
sendATcommand("AT+CREG?", "+CREG: 0,5", 500)) == 0 ); //
sets APN, user name and password
sprintf(aux_str, "AT+CGSOCKCONT=1,\"IP\",\"%s\"", apn);
sendATcommand(aux_str, "OK", 2000);
sprintf(aux_str, "AT+CSOCKAUTH=1,1,\"%s\",\"%s\"",
user_name, password);
sendATcommand(aux_str, "OK", 2000);
}
Content
Beyond
Syllabus
Using LEDs

void setup()
{
pinMode(77, OUTPUT); //configure pin 77 as
output
}
// blink an LED once
void blink1()
{
digitalWrite(77,HIGH); // turn the LED on
delay(500); // wait 500 milliseconds
digitalWrite(77,LOW); // turn the LED off
delay(500); // wait 500 milliseconds
}
Creating infinite loops
void loop() //blink a LED repeatedly
{
digitalWrite(77,HIGH); // turn the
LED on
delay(500); // wait 500 milliseconds
digitalWrite(77,LOW); // turn the LED
off
delay(500); // wait 500 milliseconds
}
Using switches and buttons
const int inputPin = 2; // choose the input pin
void setup() {
pinMode(inputPin, INPUT); // declare pushbutton as input
}
void loop(){
int val = digitalRead(inputPin); // read input value
}
Reading analog inputs and scaling
const int potPin = 0; // select the input pin for the
potentiometer
void loop() {
int val; // The value coming from the sensor
int percent; // The mapped value
val = analogRead(potPin); // read the voltage on the pot
(val ranges from 0 to 1023)
percent = map(val,0,1023,0,100); // percent will range
from 0 to 100.
Creating a bar graph using LEDs
const int NoLEDs = 8;
const int ledPins[] = { 70, 71, 72, 73, 74, 75, 76, 77};
const int analogInPin = 0; // Analog input pin const int
wait = 30;
const boolean LED_ON = HIGH;
const boolean LED_OFF = LOW;
int sensorValue = 0; // value read from the sensor
int ledLevel = 0; // sensor value converted into LED
'bars'
void setup() {
for (int i = 0; i < NoLEDs; i++)
{
pinMode(ledPins[i], OUTPUT); // make all the LED pins
outputs
}
}
Creating a bar graph using LEDs
void loop() {
sensorValue = analogRead(analogInPin); // read the analog
in value
ledLevel = map(sensorValue, 0, 1023, 0, NoLEDs); // map to
the number of LEDs
for (int i = 0; i < NoLEDs; i++)
{
if (i < ledLevel ) {
digitalWrite(ledPins[i], LED_ON); // turn on pins less
than the level
}
else {
digitalWrite(ledPins[i], LED_OFF); // turn off pins higher
than the level:
}
}
}
Measuring Temperature
const int inPin = 0; // analog pin
void loop()
{
int value = analogRead(inPin);
float millivolts = (value / 1024.0) *
3300; //3.3V analog input
float celsius = millivolts / 10; //
sensor output is 10mV per degree
Celsius
delay(1000); // wait for one second
}
Reading data from Arduino
void setup()
{
Serial.begin(9600);
}
void serialtest()
{
int i;
for(i=0; i<10; i++)
Serial.println(i);
}
Using PIR motion sensors
Using PIR motion sensors
const int ledPin = 77; // pin for the LED
const int inputPin = 2; // input pin (for the PIR sensor)
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare pushbutton as input
}
void loop(){
int val = digitalRead(inputPin); // read input value
if (val == HIGH) // check if the input is HIGH
{
digitalWrite(ledPin, HIGH); // turn LED on if motion
detected
delay(500);
digitalWrite(ledPin, LOW); // turn LED off
}
}
Using ultrasonic sensors
• The “ping” sound pulse is generated when the
pingPin level goes HIGH for two microseconds.
• The sensor will then generate a pulse that terminates
when the sound returns.
• The width of the pulse is proportional to the distance
the sound traveled
• The speed of sound is 340 meters per second, which
is 29 microseconds per centimeter. The formula for
the distance
• of the round trip is: RoundTrip = microseconds / 29
Using ultrasonic sensors
const int pingPin = 5;
const int ledPin = 77; // pin connected to LED
void setup()
{
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop()
{
int cm = ping(pingPin) ;
Serial.println(cm);
digitalWrite(ledPin, HIGH);
delay(cm * 10 ); // each centimeter adds 10 milliseconds delay
digitalWrite(ledPin, LOW);
delay( cm * 10);
}
Using ultrasonic sensors
int ping(int pingPin)
{
long duration, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// convert the time into a distance
cm = microsecondsToCentimeters(duration);
return cm ;
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
Audio output
tone(speakerPin, frequency, duration); // play the
tone
delay(duration); //wait for the tone to finish
Example
• Write a program that plays an A note (440 Hz)
for 1 second when a motion sensor detects
motion.
Using Interrupts
• On a standard Arduino board, two pins can be
used as interrupts: pins 2 and 3.
• The interrupt is enabled through the following
line:
• attachInterrupt(interrupt, function, mode)
– attachInterrupt(0, doEncoder, FALLING);
Interrupt example
int led = 77;
volatile int state = LOW;
void setup()
{
pinMode(led, OUTPUT);
attachInterrupt(1, blink, CHANGE);
}
void loop()
{
digitalWrite(led, state);
}
void blink()
{
state = !state;
}
Timer functions (timer.h library)
• int every(long period, callback)
– Run the 'callback' every 'period' milliseconds. Returns the
ID of the timer event.
• int every(long period, callback, int repeatCount)
– Run the 'callback' every 'period' milliseconds for a total of
'repeatCount' times. Returns the ID of the timer event.
• int after(long duration, callback)
– Run the 'callback' once after 'period' milliseconds. Returns
the ID of the timer event.
Timer functions (timer.h library)
• int oscillate(int pin, long period, int startingValue)
– Toggle the state of the digital output 'pin' every 'period'
milliseconds. The pin's starting value is specified in
'startingValue', which should be HIGH or LOW. Returns the
ID of the timer event.
• int oscillate(int pin, long period, int startingValue, int
repeatCount)
– Toggle the state of the digital output 'pin' every 'period'
milliseconds 'repeatCount' times. The pin's starting value is
specified in 'startingValue', which should be HIGH or LOW.
Returns the ID of the timer event.
Timer functions (Timer.h library)
• int pulse(int pin, long period, int startingValue)
– Toggle the state of the digital output 'pin' just once after
'period' milliseconds. The pin's starting value is specified in
'startingValue', which should be HIGH or LOW. Returns the
ID of the timer event.
• int stop(int id)
– Stop the timer event running. Returns the ID of the timer
event.
• int update()
– Must be called from 'loop'. This will service all the events
associated with the timer.
#include "Timer.h"
Example (1/2)
Timer t;
int ledEvent;
void setup()
{
Serial.begin(9600);
int tickEvent = t.every(2000, doSomething);
Serial.print("2 second tick started id=");
Serial.println(tickEvent);
pinMode(13, OUTPUT);
ledEvent = t.oscillate(13, 50, HIGH);
Serial.print("LED event started id=");
Serial.println(ledEvent);
int afterEvent = t.after(10000, doAfter);
Serial.print("After event started id=");
Serial.println(afterEvent);
}
Example (2/2)
void loop()
{
t.update();
}

void doSomething()
{
Serial.print("2 second tick: millis()=");
Serial.println(millis());
}

void doAfter()
{
Serial.println("stop the led event");
t.stop(ledEvent);
t.oscillate(13, 500, HIGH, 5);
}
ChipKit MAX32
• Microcontroller: PIC32MX795F512L
• Flash Memory: 512K
• RAM Memory: 128K
• Operating Voltage: 3.3V
• Operating Frequency: 80Mhz
• Typical operating current: 90mA
• Input Voltage (recommended): 7V to 15V
• Input Voltage (maximum): 20V
• I/O Pins: 83 total
• Analog Inputs: 16
• Analog input voltage range: 0V to 3.3V
• DC Current per pin: +/-18mA
• Advanced peripherals:
• 10/100 Ethernet MAC
• USB 2.0 Full Speed OTG controller
• 2 CAN controllers.
• External Interrupts: Pin 3 (INT0), Pin 2 (INT1), Pin 7 (INT2), Pin 21 (INT3), Pin 20
(INT4)
Basic I/O Shield
• Features
– 128x32 pixel OLED graphic display
– I2C temperature sensor
– 256Kbit I2C EEPROM
– I2C daisy chain connector
– 4 push buttons
– 4 slide switches
– 8 discrete LEDs
– 4 open drain FET drivers
– Analog potentiometer
Temperature Sensor
• A digital temperature sensor is provided using a Microchip
TCN75A 2-Wire Serial Temperature Sensor. The temperature
sensor, IC2, is an I2C device, and is located in the lower right
corner of the board.
• The TCN75A is rated for an accuracy of +/-1ºC and has
selectable resolution from 0.5ºC down to 0.0625ºC. The seven
bit device address is ‘1001000’.
• Digilent provides a library for accessing the temperature
sensor. This library is available on the Digilent web site and in
the third party library repository on github.
• Using the temperature sensor with the MAX32 board requires
manually connecting the SDA and SCL pins to the basic I/O
shield
Configuring Temperature sensor
• void config(uint8_t configuration)
• Parameters
• configuration - Value to be written to config register
• This function writes the configuration register with the given value. There are a number of defined
• values as described below that can be or’d together to set multiple parameters. For example if one
• wished to put the device in one shot mode and use 12 bit resolution the following call could be made.
• Config(ONESHOT | RES12)
• IOSHIELDTEMP_ONESHOT 0x80 //One Shot mode
• IOSHIELDTEMP_RES9 0x00 //9-bit resolution (0.5ºC)
• IOSHIELDTEMP_RES10 0x20 //10-bit resolution
• IOSHIELDTEMP_RES11 0x40 //11-bit resolution
• IOSHIELDTEMP_RES12 0x60 //12-bit resolution (0.0625ºC)
• IOSHIELDTEMP_FAULT1 0x00 //1 fault queue bits
• IOSHIELDTEMP_FAULT2 0x08 //2 fault queue bits
• IOSHIELDTEMP_FAULT4 0x10 //4 fault queue bits
• IOSHIELDTEMP_FAULT6 0x18 //6 fault queue bits
• IOSHIELDTEMP_ALERTLOW 0x00 //Alert bit active-low
• IOSHIELDTEMP_ALERTHIGH 0x04 //Alert bit active-high
• IOSHIELDTEMP_CMPMODE 0x00 ///comparator mode.
• IOSHIELDTEMP_INTMODE 0x02 //interrupt mode
• IOSHIELDTEMP_STARTUP 0x00 //Shutdown disabled
• IOSHIELDTEMP_SHUTDOWN 0x01 //Shutdown enabled
• IOSHEIDLTEMP_CONF_DEFAULT //Power up initial configuration
Reading Temperature sensor
• float getTemp()
• Retrieves the current temp from the temp
sensor and converts the returned value into a
signed floating point value.
Example
void setup(){
IOShieldTemp.config(IOSHIELDTEMP_ONESHOT |
IOSHIELDTEMP_RES11 | IOSHIELDTEMP_ALERTHIGH);
}

void loop()
{
float temp;
int celsius;
char sign, msd_char, lsd_char;
//Get Temperature in Celsius.
temp = IOShieldTemp.getTemp();
}
Potentiometer
• A potentiometer is provided on the board
• to be used as an analog signal source or
• analog control input. The pot is a 10Kohm
• trimmer pot connected between the VCC3V3
• supply and ground. The wiper of the pot is
• connected to analog input A0.
• The pot is read using the analogRead function.
OLED Display
• 128x32 pixels
• Each individual pixel can only be on
(illuminated) or off (not illuminated)
• The display is a serial device that is accessed
via an SPI interface.
• write-only device
Using the OLED display
• Initialization
• Mode select
– Character
– Graphic
– Drawing
Example
void setup()
{
IOShieldOled.begin();
}

void loop()
{
char toprint;

IOShieldOled.clearBuffer();
IOShieldOled.setCursor(0, 0);

toprint = ‘A’;

IOShield0led.putChar(toprint);
}
INTRODUCTION TO SENSORS
What is a sensor?
• A device that receives a stimulus and
responds with an electrical signal.
• A special type of transducer (device that
converts one type of energy into another
Common Sensors
• Mechanical
– Accelerometers
– Gyroscopes
• Optical
– Photodetectors
– Infrared
• Semiconductor
– Gas
– Temperature
– Magnetic
Example: Simple temperature sensor
• A RTD is a thermoresistive temperature
sensor. It is a metal element (in a ceramic
tube) whose resistance typically increases with
temperature, according to a known function.
• A linear approximation is given by

• Where a is the temperature coefficient, T is


the temperature in Kelvin and R0 the
resistance in a known temperature
Example
• Calculate the temperature for a copper RTD if
R0 = 500Ω and room temperature and a =
0.0043. The measured resistance is 500.43Ω
Sensor Characteristics (1/4)
• Range
– Full Scale Range
– Operating Voltage Range
• Accuracy
• Transfer Function
– S=F(x), where x is the measurand and S the electrical
signal (commonly Voltage)
• Sensitivity
– The change in input required to generate a unit
change in output
Sensor Characteristics (2/4)
• Accuracy
• Precision
Sensor Characteristics (3/4)
• Error: the difference between the measured
value and true value
• Systematic errors are reproducible
inaccuracies that can be corrected with
compensation methods
– Interference errors
– Operator errors etc.
• Random error
– Noise
Sensor Characteristics (4/4)
• Hysterysis: the difference in output between
the rising and falling output values for a given
input
Example: Smoke sensor (1/2)
• An MQ-2 smoke sensor reports smoke by the voltage
level it puts out.
• The more smoke there is, the higher the voltage.
• built-in potentiometer for adjusting sensitivity
• Three pins:
– Vdd input
– Ground input
– Analog output
Smoke sensor (2/2)
const int smokePin = 54; //sensor input
void setup() {
pinMode(smokePin, INPUT);
Serial.begin(9600);
}
void loop() {
int smoke_level = analogRead(smokePin); //read sensor
Serial.println(smoke_level);
if(smoke_level > 120) { //calibrate accordingly
Serial.println("Smoke detected");
}
delay(100); // ms
}
Signal Conditioning
• A physical sensor, like a thermocouple, produces a raw
data element (e.g., a voltage). Often, a sequence of raw
data elements is collected and an averaging algorithm is
applied to reduce the measurement error.
• In the next step the raw data must be calibrated and
transformed to standard measurement units. The term
signal conditioning is used to refer to all the processing
steps that are necessary to obtain meaningful measured
data from the raw sensor data.
• After signal conditioning, the measured data must be
checked for plausibility and related to other measured
data to detect a possible fault of the sensor.

128
void loop() {
sum = 0;
Example
//green is error control, red is signal conditioning
for(int i=0; i<10; i++){
int sum+ = analogRead(A0); //average of 10 temp measurements
delay(1650); //sensor response time
}
int value = sum/10; //value is a raw data element
//with a 10-bit ADC we get a 0 < value < 1023 for a 0 – 3.3V range
//sensor gives voltage between 100mV and 1750 mV
int mV = map(value,0,1023,0,3300); //returns mVs
if (mV < 100 || mv > 1750) // value error

else
int temp = map(mV,100,1750,-40,125); //temp is the conditioned signal

129
ACTUATORS
Actuators
• Device that turns energy (typically electrical)
to motion
• Features
– Force
– Speed
– Torque
– Power
– Efficiency
DC motor
• Force is produced
(F=ILB) due to the
electric current in a
wire inside a
magnetic field.
• Proportional to the
current, therefore can
be controlled by
potentiometer
• Hard to control
precisely
Servo motors
• A DC motor with a
control circuit
• Servo motors are
controlled by PWM
through the control pin
Servo motor control
#include <Servo.h>
Servo myservo; // create servo object to control a servo
void setup() {
int val = 180; // variable to control servo
myservo.attach(9); // pin 9 is a PWM pin
}
void loop() {
myservo.write(val); // constant servo speed
delay(15); // waits for the servo to get there
}
Stepper Motors
• motor controlled by a series of electromagnetic coils.
• The center shaft has a series of magnets mounted on it
• the coils are alternately given current or not, creating
magnetic fields which repulse or attract the magnets on the
shaft, causing the motor to rotate.
• allows for very precise control of the motor. it can be turned
in very accurate steps of set degree increments
• two basic types
– unipolar
– bipolar
Example: Unipolar stepper motor
• Four digital pins
required to
control the motor
• Darlington
transistor array
used for supplying
the power
required
Stepper motor control
#include <Stepper.h> //the control sequence is in this library
const int stepsPerRevolution = 200; // motor-dependent
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); //pins used
void setup() {
// set the speed at 60 rpm:
myStepper.setSpeed(60); //actually sets the delay between steps
}
void loop() {
// step one revolution in one direction:
myStepper.step(stepsPerRevolution);
delay(500);
}
Binary and Hexadecimal Numbers - 1

• Microcontrollers are fundamentally digital (as


opposed to ‘analog’) and use binary logic
– Two states: high and low, 1 or 0, on or off
• Often 5V or 0V
– One binary digit is called a bit
• It can take on two possible states: 1 or 0
– Eight binary digits are called a byte
– Four binary digits are called a nibble
Binary and Hexadecimal Numbers - 2
• Byte and bits

1 1 0 0 1 1 0 1
Bit No. 7 6 5 4 3 2 1 0
Upper nibble Lower nibble
(4 bits) (4 bits)

MSB LSB
(Most Significant Bit) (Least Significant Bit)
Binary and Hexadecimal Numbers - 3
Place Value

1 1 3 8 (Base 10 or decimal number)

1  103  1  102  3  101  8  100


1000  100  30 8  1138 (Base 10)

Bit No. 3 2 1 0

1 1 0 1
(Base 2 or binary number )

1 23  1 2 2  0  21  1 20
8 4 0  1  13 (Base 10)

• What range of decimal values can 4 bits represent? 0 to 15


• How many values in total can 4 bits represent? 16
Binary and Hexadecimal Numbers - 4
Binary HEX
0 0 0 0 0 Why is hex important?
0 0 0 1 1
0 0 1 0 2
One hex digit can be
0 0 1 1 3
used as shorthand to
0 1 0 0 4 represent four binary
0 1 0 1 5 digits
0 1 1 0 6
0 1 1 1 7
Two hex digits can be
1 0 0 0 8 used as shorthand to
1 0 0 1 9 represent eight
1 0 1 0 A binary digits or one
byte
1 0 1 1 B
1 1 0 0 C
1 1 0 1 D
1 1 1 0 E
1 1 1 1 F
Practice
• 0b11000111 in hex (0b is C notation that says,
“interpret what follows as a binary number”)
• 0b10011001 in hex
• 0b10011001 as a base 10 number
• 0x5A in binary (use 8 bits)
• 0b11111111 in hex and as a base 10 number
• (37)10 in binary and hex
the prefix '0x' is C notation that means that the digits which follow are hex digits
the prefix '0b' means that the digits which follow are binary digits

Back to PORT details


Solution
• 1100 0111 in hex = 0xC7
• 1001 1001 in hex = 0x99
• 1001 1001 in base 10 = 153
• 0x5A in binary = 0b0101 1010
• 0b1111 1111 = 0xFF or 255
• (37) = 0b0010 0101 or 0x25
So What?
• Recall the question:
– Is there a way change the data direction for a set of pins
all at the same time?
• All the work of MCU happens through registers
(special memory locations)
– Registers on the Atmega328 are 8-bits wide
• The data direction register (DDRx) handles the data
directions for pins in PORTx

Source:http://www.atmel.com/dyn/products/product_card.asp?PN=ATmega328P p. 93
Data Direction Register
• If the bit is zero -> pin will be an input
– Making a bit to be zero == ‘clearing the bit’
• If the bit is one -> pin will be an output
– Making a bit to be one == ‘setting the bit’
• To change the data direction for a set of pins
belonging to PORTx at the same time:
1. Determine which bits need to be set and cleared in DDRx
2. Store the binary number or its equivalent (in an alternate
base, such as hex) into DDRx
ATmega328 Registers of Interest
• See the ATmega328 data sheet, pp. 76-94
• For digital IO, the important registers are:
– DDRx
• Data Direction bit in DDRx register (read/write)
– PORTx
• PORTx data register (read/write)
– PINx
• PINx register (read only)
PORT Pin and
register details
ATmega328 datasheet, pp. 76-94

Jump to bits
Handling the Arduino - How NOT to Do It!

Improper Handling - NEVER!!!


Handling the Arduino - The Proper Way

Proper Handling - by the edges!!!


Arduino Uno R3
ATmega16u2 replaces FT232RL for USB-serial communication

http://www.adafruit.com/index.php?
main_page=popup_image&pID=50

See: http://learn.adafruit.com/arduino-tips-tricks-and-techniques/arduino-uno-faq
Arduino Due
Note: 3.3 V !!

Atmel SAM3X8E processor (32 bit ARM Cortex M3 architecture, 84MHz)

http://www.adafruit.com/index.php?main_page=popup_image&pID=1076

See: http://arduino.cc/en/Main/ArduinoBoardDue
Arduino Duemilanove/Uno Features
Microcontroller ATmega168/328
Operating Voltage 5V
Input Voltage (recommended) 7-12V
Input Voltage (limits) 6-20V
Digital I/O Pins 14 (of which 6 provide PWM output)
Analog Input Pins 6
DC Current per I/O Pin 40 mA
DC Current for 3.3V Pin 50 mA
16 KB (ATmega168) or 32 KB (ATmega328) of which 2 KB
Flash Memory
used by bootloader
SRAM 1 KB (ATmega168) or 2 KB (ATmega328)
EEPROM 512 bytes (ATmega168) or 1 KB (ATmega328)
Clock Speed 16 MHz

http://www.arduino.cc/en/Main/ArduinoBoardDuemilanove
http://arduino.cc/en/uploads/Main/arduino-duemilanove-schematic.pdf
ATmega328 Microcontroller
Pin number
Pin name

Special
function

Note the
limitations!
p. 316 Source:http://www.atmel.com/dyn/products/product_card.asp?PN=ATmega328P
Absolute Maximums

ATmega328 data sheet p. 316


Microcontroller Ports and Pins
 The communication channels
through which information flows C
into or out of the
microcontroller
 Ex. PORTB
 Pins PB0 – PB7
 May not be contiguous
 Often bi-directional See next slides!
Port Pin Data Directionality
• Input
– When you want to take information from the external
world (sensors) into the MCU
• Output
– When you want to change the state of something outside
the MCU (turn a motor on or off, etc.)
• Pins default to input direction on power-up or reset
• Your program can set or change the directionality of
a pin at any time
ATmega328
Block Diagram

Input

Output

You might also like