INTRODUCTION TO MICROCONTROLLERSAnd all that whirrs, clicks, and beeps
INSTRUCTORS
Ms. Hinterlong Lucas Sturnfield Brian Baker Thomas Houlahan
SPONSORS
Houlahan’s Tavern and Grill
PROGRAMMING LANGUAGES
.NET, Java, C++, Python…? Assembly?
WHAT MICROS CAN DO
ELECTRONICS
Electron juggling and shuffling
(some kinds of shuffling are more impressive than others)
OUTLINE Today
Basic electronics Digital electronics
Tuesday Programming a microcontroller Start projects
Wednesday Projects
Thursday Projects
Friday Projects and presentations
BASIC ELECTRONICS
BASIC ELECTRONICS - CIRCUITS
CIRCUIT DIAGRAMS
http://www.fancon.cz/slave-flash-trigger/slave-flash-en.html
WIRE AND ELEMENTS
Some elements Elements wired together
BRANCHES AND NODES
BRANCHES AND NODES
BRANCHES AND NODES
VOLTAGE AND CURRENT
Voltage Potential energy per
unit charge Measured in Volts = Joules per Coulomb Water analog:
pressure Measured between
nodes
VOLTAGE AND CURRENT
Current Flow of electrons Measured in
Amperes (Amps)= Coulombs per
Second Water analog: flow
rate Measured through
an branch (through an element)
OHM’S LAW: V = I * R
Voltage across the element = Va – Vb
Resistor has resistance R1, measured in Ohms
Current through resistor is i_R1
Va-Vb = R1 * i_R1
POWER: P = V * I
Power used by any branch is equal to the voltage across the branch multiplied by the current through that branch
Units: Joules / Coulomb * Coulomb / Second = Joules / Second = Watts
KVL AND KCL
Kirchoff’s Voltage Law The sum of voltages around any loop equals zero
KVL AND KCL
Define a ground node to be zero volts Now, each node has a voltage
KVL AND KCL
Kirchoff’s Current Law The sum of currents entering a node equals zero (a lot like mass conservation)
BREADBOARDS
Internal connections Power rails
MULTIMETERS – MEASURING VOLTAGE Multimeter must connect to circuit differently to
measure voltage or current To measure voltage, set multimeter to Voltage setting,
and place leads in parallel with branch of interest
MULTIMETERS – MEASURING CURRENT
To measure current, set multimeter to Current setting, and place leads in series with branch of interest
SERIES AND PARALLEL RESISTANCE
DIODES AND LEDS
Water analog: Check valve – only lets current flow one way
Either ON or OFF On
Anode-cathod voltage is fixed value, no matter what current (0.7 V)
Off Current is zero, no matter what
voltage LEDs emit light when ON
LEDS AND CURRENT LIMITING RESISTORS
RECAP
Voltage is potential energy (pressure) Current is flow of electrons (flow rate) Voltage is measured between nodes, or with
respect to ground Current is measured through branches
V=IR P=IV
VOLTAGE ISN’T ALWAYS CONSTANT
Speakers are driven by a voltage signal; settings the voltage sets the position of the speaker diaphragm
SENSORS AND ANALOG OUT
Some sensors vary an output voltage; the voltage corresponds to a sensor value
Maxbotix ultrasonic sensor outputs voltage corresponding to distance
RF - RADIO
Radio uses Electromagnetic waves Voltage on antenna varies Waveform carries data
POWER: DC VS AC
Direct Current Batteries, wall warts Time-constant
voltage Current flows one
way
Alternating Current Electrical outlets Time-varying
voltage Current flows
different ways at different times
Transfers power great distances with low line loss
DC AC
AC TO DC
http://hyperphysics.phy-astr.gsu.edu
LM7805 Volage regulator - takes ~9V DC, makes 5V DC
CAPACITOR
Stores energy Resists change in voltage Electrolytic are polarized,
have stripe on minus end Capacitance is measured in
Farads (typically, micro Farads)
Ceramic capacitorElectrolytic capacitor
TRANSISTOR
Considered by many to be greatest invention of the 20th century
Transistor as amplifier (radio) Transistor as switch
DIGITAL ELECTRONICS0110100001100101011011000110110001101111001000000111011101101111011100100110110001100100
(hello world)
1 AND 0
Digital logic doesn’t use analog voltages – only ‘high’ and ‘low’ have meaning Typically 5V and 0V Sometimes 3.3V and 0V Computer processor High is 1, Low is 0
MICROCONTROLLER
Programmable Chip Same idea as PC, but
on much smaller scale
BLACK BOX
Black box does stuff to inputs to get outputs Typically don’t want to care what happens
inside black box; just need to know how to give it input, and what output to expect
BLACK BOX
Need to know where to put toast Need to know to be careful getting toast; it’s
hot Need to know that ‘ding’ means toast is done Ding is an output! Power, timer setting, lever are all inputs
COMPUTER VS MICROCONTROLLER
Inputs Keyboard Mouse Microphone
Outputs Monitor Speakers
Black box Program is written
on the computer
Inputs Voltage on pins
Outputs Voltage on pins
Black box Program is written
on a computer and downloaded to the chip
Computer Microcontroller
WHY MICROCONTROLLERS?
Low cost for a lot of processing Low power (can run on batteries)
If power is well managed, can run for years on a 9V!
Small Can communicate with PCs to do complex
processing with real world effects
BLINKY LED IN A BREADBOARD
Breadboard stuff PICS are already programmed Remember: Electrolytic caps are polarized;
stripe goes to lower voltage When you apply power, LED should blink
PCB
Haha! jk jk we have awesome pcb. Let’s solder:
Soldering irons get HOT: don’t burn yourself Tinning things: put a little solder on both pieces
that you’ll connect, THEN connect them Sockets are done you get to do caps and 7805
With sockets, we don’t apply heat to a chip. Also, if the chip gets fried, we can pull it and put a new one in
Test with Blinky LED again
INTRODUCTION TO MICROCONTROLLERS
PROGRAMMING A PICMaking machines Think
ARCHITECTURE
Memory Variables – ‘registers’ – all 1 byte big F register
Declare you own Special ones, like PORTD and TRISB
Working register – the accumulator – your ‘hands’
Instructions Processor only does ONE thing at time – moves
from one instruction to the next Each instruction has an opcode (action) and
parameters i.e., movfw PORTA
CO
NFIG
& V
AR
IAB
LES
Comments prefixed with semilcolons
Compiler info
Config bits
Constants
Variables – declared two different ways
BEG
INN
ING
OF C
OD
E
ORG declares a place in code memory
0x000 is restart
0x004 is interrupt
(ignore interrupt for now)
Now every line is a comment, label, or instruction
nop – do nothing
goto [label] – jumps to a named label
INIT
IALIZ
ATIO
N
bcf and bsf – bit modification
Special f registers and bank bits
Moving through accumulator
PORT and TRIS control pins
ADCON1 and analog
TH
E A
CTU
AL L
ED
BLIN
KIN
G C
OD
E
Turn it on
Wait using a subprocedure (goto and return)
Turn it off
Wait using sub
Loop back & main program loops
TH
E D
ELAY
SU
BP
RO
CED
UR
E
Some calculated exact cycle usage (it’s deterministic – depends on clock frequency!)
Involves looping and counting down a bunch – takes a lot less room than 5000000 nop instructions!
Note ‘return’ statement
END statement is end of our code
Branching – no IF; decfsz (also, btfss/btfsc)
ADDING A BUTTON
We have processing and output, let’s add an input
DEBOUNCING
Voltage doesn’t switch all that cleanly
Our PIC is faster than the debounce!
Solutions Hardware – add a
capacitor to filter Software – poll
button again a set time after it first changes
CODE CHANGES
TRISB bit 0 should be 1 for an input! movlw b’00000001’ movwf TRISB
Completely different loop New (shorter) delay functions (please excuse
the messy code!) We’ll have the PIC turn LED at PORTD,7 on or
off when pressed, like a lightswitch
BU
TTO
N L
OO
P
Check to see if button changes – if it does, go to double check
doubleCheck waits about 2ms and then checks button again. If not pressed, go back, if pressed, go on
setLED or clearLED depending on LED state
Then, wait for button release before checking for another button press
PROGRAMMING THE PIC
Project -> Build All (F10)
Can has Build Succeeded?
Don’t need to download each time; compiling can help you find errors
If it’s the only option: Programmer->-> Select Programmer -> PICkit 2
Then, Plug in PICkit 2 to
header Programmer->-> Program
Compile Download
DEBUGGING The PIC is a really
good black box You don’t get info out
of it unless you code it to output info!
LEDs can be useful for tracking what state the PIC is in
For more complex info, communication with a computer is the way to go
Extra credit for laughing at my visual puns!
SERIAL/COM/UART/RS232
Uses 9 pin connector Only 3 are used – Gnd, Rx, Tx
Many new computers don’t have this connector USB to Serial adapter are widely available
PIC has built in module for this (UART) Libraries for Serial Hyperterminal
SERIAL COMMUNICATION: COMPUTER SIDE
Serial ports show up as COM ports (COM1, COM2, etc)
You can write your own programs
Hyperterminal is easy to use for simple things (including debugging)
ASCII table
SERIAL COMMUNICATION: COMPUTER SIDE
Name connection Select COM Port Settings
9600 baud is commonly used
To see what you type, File -> Properties ASCII Setup… button Check ‘Echo typed
characters locally’
SERIAL COMMUNICATION: PIC SIDE
RS232 standard 1 is -12V, 0 is 12V
We usually just want or have 5V supply, not 24V split in the middle!
MAX232 handles inversion and voltage boosting
SER
IAL C
OD
E
Enabling Serial communication on the 877a is a matter of setting up the associated f-registers. SPBRG stores a value that corresponds to 9600 baud, enable bits are set, etc
Documentation for how to do this (for other modules, too) is in the 877a datasheet
SERIAL CODE To transmit, load a value
into TXREG Values for ASCII letters can
be found at asciitable.com Before transmitting again,
wait for transmit to finish with waitForTX
To receive, call waitForRX – it puts received value into w (and variable rxData) Be careful using; it stops
everything until a character is received! There are other ways to
deal with this
ALU
Arithmetic Logic Unit Handles instructions like addwf, subwf, incf,
decf, rrf, rlf, etc After performing operation, some bits in in
STATUS might change: Z, C, DC If Z is set, result was zero If C is set, carry occurred (or, for a situation
where a borrow might occur, 0 if the borrow occurred) Also stores bits that ‘fall off’ from rrf and rlf
ALU
To test if two things are equal, movfwthing1 subwf thing2, w ;make sure result is stored in w! btfss STATUS, Z goto not_equal goto equal
rrf and rlf are rotate right and rotate left through carry Always bcf or bsf STATUS, C before doing rrf or
rlf!
COMPONENTSA part bin fit for Frankenstein
THREE CATEGORIES
Inputs (Sensors)OutputsProcessing
COMMUNICATION These inputs and/or
outputs RF
Sparkfun has some modules
Bluetooth Appear as COM port on
computer Sparkfun +: Current wireless
protocol, devices for cell phones (Android!)
-: $$$ RFID
TINY circuits, powered by antennae
Not all standardized Implants Key cards
SENSORS - LIGHT
Photocells Resistance
decreases with more light
IR Receivers Communication Coupled with IR
LEDs, can do rangefinding
PIR Motion Sensing CCD Cameras
SENSORS - POTENTIOMETERS
Variable resisters Depending on
control’s position, resistance changes
Usually have a split design – 3 pins. Resistance from 1 to 2 plus that from 2 to 3 is always the same; put power at 1 and 3, and voltage at 2 varies
SENSORS - ULTRASONIC
Maxbotix makes easy to use ultrasonic rangefinders Different
sensitivities Can be daisy-
chained Analog, Serial, and
Pulse-width outputs ~$30 each
SENSORS - TEMPERATURE
Thermocouple Voltage corresponds
to temperature +: Cheap,
standardized -: Nonlinear!
Maxim OneWire Actually pretty
complicated Can set ‘alarm’ temps,
0.5 degrees C resolution
SENSORS - BUTTONS Tact switches
+ Cheap! Standardized
- Small, not pretty Keypads
+ Can look awesome - Weirder to interface
with Videogame
controllers Can wire directly to
buttons, analog sticks PS2 interface is
known
SENSORS - WIIMOTE
Communicates with Bluetooth Computer drivers
have been developed
Even better, Nunchuck uses I2C 3-axis accel, analog
stick, and two buttons for $20
PCB interface available (FunGizmos.com)
SENSORS – ACCELEROMETERS AND GYROSCOPES
There are MEMS Gyroscopes + small, interface with
electronics easily - $$$
Used together, accels & gyroscopes provide data to do position tracking There’s some drift Some serious number
crunching needs to be done to track in real time
SENSORS - GPS
+ Tons of fun data! - Ceiling interferes,
and $$$ (They DID pay to put
a bunch of satellites in orbit…) (Plus they crunch a
lot of numbers)
SENSORS – TOUCHPADS, MICE, KEYBOARDS
Lots of Multitouch interfaces
Mice & Keyboards – PS2 interface
SENSORS - OTHER
Alcohol Gas Barometric If you look hard
enough, you’ll probably find what you’re looking for
Mic & voice recognition - SAPI
Cameras & Computer Vision - OpenCV
OUTPUTS – ON/OFF Simply turning things
on and off can be an output Triacs for controlling
120V AC Working with 120V AC
is MUCH MORE DANGEROUS – never work on a live circuit
Brian used MAC15A8 triacs, and MOC3012 / NTE3047 drivers
Transistors for DC NPN goes at bottom,
PNP goes at top
OUPUTS – LEDS AND 7 SEGMENT LCDS LEDs are fun
+ Cheap! Add a coin cell battery, a
magnet, and some scotch tape, and you have an LED throwie
Developed by Graffiti Researh Lab
EL wire Electroluminescent wire Requires a special driving
inverter, but whole wire lights up
7-Segs Very commonly used,
pretty cheap Really just a bunch of LEDs Driver ICs are available:
put in a number, it displays it
OUTPUTS – CHARACTER & GRAPHIC LCDS
Character LCDs A little more
complicated, but great for displaying info The blue ones look cool
Graphic LCDs Abundant, because of
cell phones Much more complicated
to work with, but much more possibility Some dude had an AVR
micro displaying very basic 3D graphics
OUTPUTS - PROJECTORS
Pretty much necessitates a computer, but can do cool things GRL’s laser pointer
graffiti
OUTPUTS – BUZZERS, PELTIER, OTHERS… Piezoelectric buzzer
Very very common Speakers Peltier heater/cooler
Apply power one direction, and one side gets cool, the other gets hot
Apply power the other way, first side gets hot and second gets cool
Vibration Motors DC motor with off-
center weight on shaft Pneumatics & Hydraulics
Electrically controlled valves
OUTPUT – REGULAR DC MOTORS You set POWER, which
corresponds to SPEED, with a constant load
Apply power one way, and they turn that way. Apply power the other way, they turn the other way
Geared DC are often desired; without gearing, the motors have high speed but VERY low torque
Setting direction electronically requires a circuit called an H-Bridge
OUTPUT – SERVOS AND STEPPERS Servo motors
You set ANGLE Less than 360 degree
swing 3 pins: power, ground,
and analog voltage corresponding to angle (can use PWM)
Stepper motors You set POSITION Continuous rotation More complicated to
drive; must step pins in a sequence, i.e. 0001 to 0011 to 0010 to 0110 to 0100 etc
Separate driver ICs are available
PROCESSING Optoisolators EEPROM
Extra data storage Usually has I2C interface SD cards are apparently decently easy to interface with, too
Shift Registers Extra IO pins Use 2 or 3 pins on micro to control 8 pins on shift register. Daisy
chain to control 16, 24, etc… Tradeoff is speed: changing even one pin takes time to set them
all 7 Seg drivers
Give it a number, it turns on correct LEDs in 7 seg H-Bridge
Given logic inputs and power inputs, can connect a pin to + power or ground
Needed because a single transistor just connects the pin to + power or nothing (or, alternatively, ground or nothing)
PROCESSING Stepper drivers
Provide power, tell it to step one direction or the other, it handles the rest
PWM chips Provides more PWM channels
DACs and ADCs ADC common on PICs, but DAC isn’t. PWM can be used to
approximate And/Or/Not gates
Very basic logic circuits – useful in some situations to save IO pins (Chalkzilla example)
555 timers By choosing different resistors and capacitors to hook up to it,
you can set the pulse width, pulse delay, etc Op-Amps
These are a big deal All sorts of analog magic: amplification, subtraction, addition,
derivatives, integrals, isolation Beyond the scope of this. Take Electronics at IMSA!
PROJECTS