What is a Microcontroller?
Concepts: INPUT vs. OUTPUT
Referenced from the perspective of the microcontroller (electrical board).
Inputs is a signal / information Output is any signal exiting the
going into the board. board.
Almost all systems that use physical computing will have some form of output
What are some examples of Outputs?
Concepts: INPUT vs. OUTPUT
Referenced from the perspective of the microcontroller (electrical board).
Inputs is a signal / information Output is any signal exiting the
going into the board. board.
Examples: Buttons Switches, Light Examples: LEDs, DC motor, servo
Sensors, Flex Sensors, Humidity motor, a piezo buzzer, relay, an RGB
Sensors, Temperature Sensors… LED
Programming Concepts: Variable Types
• Variable Types:
8 bits 16 bits 32 bits
byte int long
char unsigned int unsigned long
float
What is a Microcontroller?
ANALOG
INPUTS
What is the difference between a ‘Digital Input’ and an ‘Analog Input’?
http://www.freescale.com/files/microcontrollers/doc/ref_manual/M68HC05TB.pdf
Examples (Arduino)
This creates an infinite loop
without the programmer
void loop (){ using a goto (which is bad
digitalWrite(77,HIGH); programming practice)
delay(500);
digitalWrite(77, LOW); These turn pin 77 on
and off (assuming
}
there is something
like a LED there
without using logic
instructions and I/O
ports
This creates a half-
second (500 ms)
delay without directly
accessing the timers
Setting the Pin Data Direction
• Arduino
• pinMode(pin_no., dir)
• Ex. Make Arduino pin 3 (PD3) an output
• pinMode(3, OUTPUT);
• pinMode(PIN_D3, OUTPUT); // with me106.h
• Note: one pin at a time
• Suppose you wanted Arduino pins 3, 5, and 7 (PD3, PD5, and PD7) to be
outputs?
• Is there a way to make them all outputs at the same time?
• Yes! Answer coming later…
Solution #1
Solution #2
Pin Voltages
• 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)
Pin Used as an Output
• Turn on an LED, which is connected
to pin Arduino pin 0 (PD0) (note the ATmega328
resistor!)
• What should the data direction be for pin 0 (PD0)? Arduino
• pinMode(____, ____); pin 0
• Turn on the LED (PD0)
• 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
• Ex. Seat belt sensor ATmega328
• Detect the switch state
• What should the data direction be for Arduino pin 3 (PD3)?
• pinMode(____, ____); Arduino
• What will the voltage be on PD3 when the switch is closed? pin 3
• What will the voltage be on PD3 when the switch is open? (PD3)
• Indeterminate!
SPST
pinMode(3, INPUT);
momentary
Pull up resistor?
Pull down resistor?
Pins as Inputs and Pull-up Resistors - 2
• Switch as a sensor, cont.
• Make the voltage on the pin ATmega328
determinate by turning on the pull-up VTG= +5V
resistor for PD3
• Assuming PD3 is an input:
• digitalWrite(PIN_SWITCH,HIGH); 1
PD3
turns on the “pull-up” resistor
0
• pinMode(PIN_SWITCH,INPUT_PULLUP);
• What will the voltage on PD3 be when the
switch is open?
• VTG
• What will the voltage on PD3 be when the
switch is closed?
Pins as Inputs and Pull-up Resistors - 3
• Switch as a sensor, cont.
• To turn off the pull-up resistor ATmega328
• Assuming PD3 is an input:
digitalWrite(PIN_SWITCH,LOW); VTG= +5V
turns the “pull-up” resistor off
1
PD3
0
PWM
Fading in and Fading Out
(Analog or Digital?)
• A few pins on the Arduino allow for us to modify the output to mimic
an analog signal.
• This is done by a technique called:
• Pulse Width Modulation (PWM)
Concepts: Analog vs. Digital
•To create an analog signal, the microcontroller uses a technique called
PWM. By varying the duty cycle, we can mimic an “average” analog
voltage.
•Pulse Width Modulation (PWM)
Project #2 – Fading
Introducing a new command…
•analogWrite(pin, val);
•
•pin – refers to the OUTPUT pin
(limited to pins 3, 5, 6, 9, 10, 11.) –
denoted by a ~ symbol
•val – 8 bit value (0 – 255).
• 0 => 0V | 255 => 5V
Move one of your LED pins over to Pin 9
• In Arduino, open up:
• File → Examples → 01.Basics → Fade
Fade - Code Review
Fade - Code Review
Delay, interrupt, timer
DELAY (1/3)
• Delays are essential in embedded systems, unlike high-performance
systems where we want the program to execute as fast as possible
• Delays are used to synchronize events, or read inputs with a specific
sampling freqency (more on Bus/Wait I/O)
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
DELAY (3/3)
• Okay, so how do we build a delay function?
• Our reference is the system clock frequency
• We use a register or a timer to measure ticks
• Each tick is 1/frequency
• Example: Assuming a 16-bit processor, an increment and a jump
instruction is 1-cycle each and a 10 MHz system clock, build a 1-sec delay:
• T = 1/10 MHz = 100 ns
• 1 s/100 ns = 10,000,000
int i=5000000; //2 ticks per iteration
BACK: i--;
if (i!=0) goto BACK;
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.
Example (1/2)
#include "Timer.h"
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);
}
Sensor
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
}
References
• M.J. McGrath, C. N. Scanaill and D. Nafus, “Sensor
Technologies Healthcare, Wellness and
Environmental Applications”, Apress, 2013
• C.W. de Silva, “Sensors and Actuators: Control
System Instrumentation”, 2nd Edition, CRC Press,
2015
• T. Karvinen and K. Karvinen, ” Make: Sensors: A
Hands-On Primer for Monitoring the Real World
with Arduino and Raspberry Pi”, Maker Media, Inc,
2014
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.
46
Example
void loop() {
sum = 0; //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
47
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);
}