Post on 04-Jan-2016
transcript
Lecture 7: Microcontrollers & I/O
Bryan Burlingame
14 October 2015
Smart, connected products require a rethinking of design. At the most basic level, product development shifts from largely mechanical engineering to a true interdisciplinary systems engineering.Porter, M., & Happelmann, J. (2015, October). How Smart, Connected Products Are Transforming Companies. Harvard Business Review, 96-112, 114.
Announcements Exam in two weeks
This is the final lecture which will be on the exam
Homework #3 due up front Homework #4 (exam review) posted
Due with the mid-term Read Ch. 3 -4 in text Open lab Wednesday evenings, 5:15
Eng 213 Arduino lab kits available from Eric Wertz
The Plan for Today How can I interact with the user
Obtaining input from the keyboard Brief decisions
Microcontrollers for engineering applications What is a microcontroller? How are microcontrollers used? The Arduino hardware platform The Spartronics Experimenter board Programming the Arduino
5
scanf() function (just a brief treatment!)
scanf() is like the reverse of printf It reads data entered via the keyboard Similarities to printf():
Needs a format string first Many common format specifiers, which indicate the type of
data expected from the keyboard Which must match the data arguments
Any number of data arguments Differences from printf():
Data argument identifiers must be preceded with an ampersand (&)
The & ahead of the variable signifies the address in memory where the data will be stored (its a pointer to the variable)
Beware!!! Forgetting the & is a common error. More on the & later this semester
6
scanf() function, cont. Differences from printf(), cont.:
Characters other than a conversion string, a space, a newline character, or a vertical tab must match characters in the input stream
A space, horizontal tab, or newline character in the format string causes scanf() to skip over leading white space up to the next nonspace character
scanf(“Distance= %lf", &num1); Will skip leading spaces before the value num1 Must find a match to the string literal, Distance= (or else
it will stop reading the input and will return the number of successful conversions that were stored (try entering a space before typing Distance=)
Darnell & Margolis (1996)
7
scanf example Prompt the user for two floating point numbers, and store them in
floating point variables of type double named x and y
#include <stdio.h>int main( void ){ float x = 0; float y = 0; char buffer[BUFF_SIZE]; printf( "Enter two floats (x y): "); scanf( "%f %f", &x, &y ); printf( “You entered %f and %f\n”, x, y ); return 0;}
More robust input We use two commands to properly obtain
input from the keyboard fgets & sscanf fgets places data collected form the
keyboard into a buffer stored as a character string up to a carriage return (when the user presses return or enter)
fgets( buffer, sizeof(buffer), stdin );
Formatted Input (2)
sscanf is from the *scanf family We’ll use fscanf later in the semester
sscanf splits the input into variables Uses conversion metasymbols like scanf sscanf( buffer, “%d %f”, &x, &y); Avoids many (though not all) weaknesses
in scanf Realistically, don’t use scanf… well ever
Formatted Input (3)#include <stdio.h>#define BUFF_SIZE 100 //note symbolic const
int main( void ){ float x = 0; float y = 0; char buffer[BUFF_SIZE]; printf( "Enter two floats (x y): "); fgets( buffer, sizeof(buffer), stdin ); sscanf( buffer, "%f %f", &x, &y ); printf( “You entered %f and %f\n”, x, y ); return 0;}
Flow control
These Boolean operations are used along with flow control (or branching) statements to control the flow of a program
DecisionsTrue False
Simple if - exampleint speed = 5; if( speed > 65 ){ // do everything until the closing }
printf( “You are speeding!\n” );} // technically, when one statement is between // the curly braces, the braces are optional. // Even so, don’t omit themelse{ // note the indentation.
printf( “You are not speeding\n” );}
What is a Microcontroller?
A small computer usually implemented on a single IC that contains a central processing unit (CPU), some memory, and peripheral devices such as counter/timers, analog-to-digital converters, serial communication hardware, etc.
http://www.amazon.com/AVR-Pin-20MHz-32K-ATMega328/dp/B004G5AVS6
ATmega328the ‘brain’ of the Arduino
Where are Microcontrollers Used?
Everywhere! Car (50 – 70 per car! (EDT Design News, July 2009))
Phone Toothbrush Microwave oven Copier Television PC keyboard Appliances
The Arduino Platform Atmel ATmega328
microcontroller 14 digital I/O pins
6 with PWM 6 analog I/O pins 32 kB (-2 kB)
Flash memory 2 kB RAM 1 kB EEPROM 16 MHz clock $10 - $30 built
$13 ‘breadboardable’
FTDIUSB chip
Digital Pins
Analog Pins
USBjack
Microcontrollerpowerjack
Voltageregulator
Pwr/GND Pins
ICSPHeader
ResetButton
PowerLED
Pin 13 LEDRx + TxLEDs
http://arduino.cc/
The Spartronics Experimenter Board Momentary SPST
push-button switches Red LEDs Piezo speaker Potentiometer (pot) Temperature sensor Light sensor RGB LED
http://www.sparkfun.com/commerce/images/products/00105-03-L_i_ma.jpg
Cathode
R
GB
speaker
Pot
RGB LED
Light sensor
Handling the Arduino - How NOT to Do It!
Improper Handling - NEVER!!!
Handling the Arduino - The Proper Way
Proper Handling - by the edges!!!
Recall: Fundamental Flow of a C Program
Start
Main
EndReturn value to Operating System (very important!)
Calling parametersAvailable from Operating System
Fundamental Flow of an Arduino Program
Start
Setup
Loop
End
Programming the Arduino An arduino program == ‘sketch’
Must have: setup() loop()
setup() configures pin modes and
registers loop()
runs the main body of the program forever
like while(1) {…} Where is main() ?
Arduino simplifies things Does things for you
/* Blink - turns on an LED for DELAY_ON msec, then off for DELAY_OFF msec, and repeats*/const byte ledPin = 13; // LED on digital pin 13const int DELAY_ON = 1000;const int DELAY_OFF = 1000;
// setup() method runs once, when the sketch starts
void setup(){ // initialize the digital pin as an output: pinMode(ledPin, OUTPUT); }
// loop() method runs forever,// as long as the Arduino has power
void loop() { digitalWrite(ledPin, HIGH); // set the LED on delay(DELAY_ON); // wait for DELAY_ON msec digitalWrite(ledPin, LOW); // set the LED off delay(DELAY_OFF); // wait for DELAY_OFF msec}
Using setup() A digital pin can either be
an output or an input Output
your program determines what the voltage on a pin is (either 0V (LOW or logic 0) or 5V (HIGH or logic 1)
Information is sent out Input
the world outside the microcontroller determines the voltage applied to the pin
Information is taken in
const byte ledPin = 13; // LED on digital pin 13
void setup(){ // initialize the digital pin as an output: pinMode(ledPin, OUTPUT); }
where can you find out aboutthe commands, etc?
http://arduino.cc/en/Reference/Extended
pinMode() sets whether a pin is an
input or an output ledPin byte constant
assigned the value of 13 OUTPUT is a macro
defined constant Which has the value 1
INPUT is a macro … ?
Blinking the LED in loop() digitalWrite()
Causes the voltage on the indicated pin to go HIGH (+5V) or LOW (0V)
Note: must first configure the pin to be an output
To make pin go to 5V (high): digitalWrite(pin_num,HIGH);
Best to #define pin num. To make pin go to 0V (low):
digitalWrite(pin_num,LOW);
delay() Causes the program to wait for
a specified time in milliseconds
#define LED_PIN 13 // LED on digital pin 13#define DELAY_ON 500 // in ms#define DELAY_OFF 100
void setup(){ // initialize the digital pin as an output: pinMode(LED_PIN, OUTPUT); }void loop() { digitalWrite(LED_PIN, HIGH); // turn LED on delay(DELAY_ON); // wait for DELAY_ON ms digitalWrite(LED_PIN, LOW); // turn LED off delay(DELAY_OFF); // wait for DELAY_OFF ms}
http://arduino.cc/en/Reference/Extended
Spartronics Experimenter LED Pinout
Pin and LED map 11 - LED0 (red) or RGB (red) 9 - LED1 (red) or RGB (green) 6 - LED2 (red) or RGB (blue) 3 - LED3 (red) 13 - LED on Arduino
Jumper determines whether pins map to red LEDs or the RGB
11 9 6 3
13 12 11 10 9 8 7 6 5 4 3 2 1 0
SCK MISO MOSI SS OC1 ICP AIN1 AIN0 T1 T0 INT1 INT0 TXD RXD
LED LED LED
Pwm pwm pwm pwm pwm pwm
LED0 LED1 LED2 LED3
Red Green Blue (v1 red)
Piezo
servo
SW0 SW1 SW2 speaker SW3
Spartronics Experimenter Digital Pin Assignments
12 8 7 4
Spartronics Experimenter Button Pinout
Pin and Button map 12 - SW0 8 - SW1 7 - SW2 4 - SW3
How should the associated pins be configured: as INPUTS or as OUTPUTS?
‘Active LOW’ Voltage on pin changes
from 5V to 0V when switch is pressed
Need to turn on internal ‘pull-up’ resistor, so that 5V is supplied to pin
To ATmega328
Pull-up Resistor Concept
ATmega328
PD3
VTG= +5V
0
1
ATmega328
PD3
VTG= +5V
0
1
Pull-up resistor OFF Pull-up resistor ON
Pull-up resistor
Simple if – example (Arduino)#define BUTTONPIN 12#define LEDPIN 3int buttonState = 0;void setup(){
pinMode( LEDPIN, OUTPUT );pinMode( BUTTONPIN, INPUT_PULLUP );
}void loop(){
int buttonState = digitalRead( BUTTONPIN );if( buttonState == LOW ) //note double == for equivalence{ //If the button is pressed, turn on the LED
digitalWrite( LEDPIN , HIGH);} else{ // otherwise, turn it off
digitalWrite( LEDPIN , LOW);}
}
References
Microcontroller. (2009, November 20). In Wikipedia, the free encyclopedia. Retrieved November 21, 2009, from http://en.wikipedia.org/wiki/Microcontroller
Arduino Home Page. (2009, November 21). Retrieved November 21, 2009, from http://arduino.cc/