# I NTRODUCTION TO M ICROCONTROLLERS And all that whirrs, clicks, and beeps.

## Presentation on theme: "I NTRODUCTION TO M ICROCONTROLLERS And all that whirrs, clicks, and beeps."— Presentation transcript:

I NTRODUCTION TO M ICROCONTROLLERS And all that whirrs, clicks, and beeps

I NSTRUCTORS Ms. Hinterlong Lucas Sturnfield Brian Baker Thomas Houlahan

S PONSORS Houlahans Tavern and Grill

P ROGRAMMING L ANGUAGES.NET, Java, C++, Python…? Assembly?

WHAT M ICROS CAN DO

E LECTRONICS Electron juggling and shuffling (some kinds of shuffling are more impressive than others)

O UTLINE Today Basic electronics Digital electronics Tuesday Programming a microcontroller Start projects Wednesday Projects Thursday Projects Friday Projects and presentations

B ASIC E LECTRONICS

B ASIC E LECTRONICS - C IRCUITS

C IRCUIT D IAGRAMS http://www.fancon.cz/slave-flash-trigger/slave-flash-en.html

W IRE AND E LEMENTS Some elements Elements wired together

B RANCHES AND N ODES

V OLTAGE AND C URRENT Voltage Potential energy per unit charge Measured in Volts = Joules per Coulomb Water analog: pressure Measured between nodes

V OLTAGE AND C URRENT Current Flow of electrons Measured in Amperes (Amps) = Coulombs per Second Water analog: flow rate Measured through an branch (through an element)

O HM S L AW : 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

P OWER : 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 Kirchoffs 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 Kirchoffs Current Law The sum of currents entering a node equals zero (a lot like mass conservation)

B READBOARDS Internal connections Power rails

M ULTIMETERS – M EASURING V OLTAGE 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

M ULTIMETERS – M EASURING C URRENT To measure current, set multimeter to Current setting, and place leads in series with branch of interest

S ERIES AND P ARALLEL R ESISTANCE

D IODES AND LED S 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

LED S AND C URRENT L IMITING R ESISTORS

R ECAP 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

V OLTAGE ISN T ALWAYS C ONSTANT Speakers are driven by a voltage signal; settings the voltage sets the position of the speaker diaphragm

S ENSORS 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

P OWER : 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 DCAC

AC TO DC http://hyperphysics.phy-astr.gsu.edu LM7805 Volage regulator - takes ~9V DC, makes 5V DC

C APACITOR Stores energy Resists change in voltage Electrolytic are polarized, have stripe on minus end Capacitance is measured in Farads (typically, micro Farads) Ceramic capacitor Electrolytic capacitor

T RANSISTOR Considered by many to be greatest invention of the 20 th century Transistor as amplifier (radio) Transistor as switch

D IGITAL E LECTRONICS 0110100001100101011011000110110001101111001000000111011101101111011100100110110001100100 (hello world)

1 AND 0 Digital logic doesnt 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

M ICROCONTROLLER Programmable Chip Same idea as PC, but on much smaller scale

B LACK B OX Black box does stuff to inputs to get outputs Typically dont want to care what happens inside black box; just need to know how to give it input, and what output to expect

B LACK B OX Need to know where to put toast Need to know to be careful getting toast; its hot Need to know that ding means toast is done Ding is an output! Power, timer setting, lever are all inputs

C OMPUTER VS M ICROCONTROLLER 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 ComputerMicrocontroller

W HY M ICROCONTROLLERS ? 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

B LINKY LED IN A B READBOARD 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. Lets solder: Soldering irons get HOT: dont burn yourself Tinning things: put a little solder on both pieces that youll connect, THEN connect them Sockets are done you get to do caps and 7805 With sockets, we dont 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

I NTRODUCTION TO M ICROCONTROLLERS

P ROGRAMMING A PIC Making machines Think

A RCHITECTURE 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

C ONFIG & V ARIABLES Comments prefixed with semilcolons Compiler info Config bits Constants Variables – declared two different ways

B EGINNING OF C ODE 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

I NITIALIZATION bcf and bsf – bit modification Special f registers and bank bits Moving through accumulator PORT and TRIS control pins ADCON1 and analog

T HE A CTUAL LED B LINKING C ODE Turn it on Wait using a subprocedure (goto and return) Turn it off Wait using sub Loop back & main program loops

T HE D ELAY S UBPROCEDURE Some calculated exact cycle usage (its 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)

A DDING A B UTTON We have processing and output, lets add an input

D EBOUNCING Voltage doesnt 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

C ODE CHANGES TRISB bit 0 should be 1 for an input! movlw b00000001 movwf TRISB Completely different loop New (shorter) delay functions (please excuse the messy code!) Well have the PIC turn LED at PORTD,7 on or off when pressed, like a lightswitch

B UTTON L OOP 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

P ROGRAMMING THE PIC Project -> Build All (F10) Can has Build Succeeded? Dont need to download each time; compiling can help you find errors If its the only option: Programmer-> -> Select Programmer -> PICkit 2 Then, Plug in PICkit 2 to header Programmer-> -> Program CompileDownload

D EBUGGING The PIC is a really good black box You dont 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!

S ERIAL /COM/UART/RS232 Uses 9 pin connector Only 3 are used – Gnd, Rx, Tx Many new computers dont have this connector USB to Serial adapter are widely available PIC has built in module for this (UART) Libraries for Serial Hyperterminal

S ERIAL C OMMUNICATION : C OMPUTER 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

S ERIAL C OMMUNICATION : C OMPUTER 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

S ERIAL C OMMUNICATION : 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

S ERIAL C ODE 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

S ERIAL C ODE 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 subwfthing2, w ;make sure result is stored in w! btfssSTATUS, Z gotonot_equal gotoequal rrf and rlf are rotate right and rotate left through carry Always bcf or bsf STATUS, C before doing rrf or rlf!

C OMPONENTS A part bin fit for Frankenstein

T HREE C ATEGORIES Inputs (Sensors) Outputs Processing

C OMMUNICATION 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

S ENSORS - L IGHT Photocells Resistance decreases with more light IR Receivers Communication Coupled with IR LEDs, can do rangefinding PIR Motion Sensing CCD Cameras

S ENSORS - P OTENTIOMETERS Variable resisters Depending on controls 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

S ENSORS - U LTRASONIC Maxbotix makes easy to use ultrasonic rangefinders Different sensitivities Can be daisy-chained Analog, Serial, and Pulse-width outputs ~\$30 each

S ENSORS - T EMPERATURE Thermocouple Voltage corresponds to temperature +: Cheap, standardized -: Nonlinear! Maxim OneWire Actually pretty complicated Can set alarm temps, 0.5 degrees C resolution

S ENSORS - B UTTONS 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

S ENSORS - W IIMOTE 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)

S ENSORS – A CCELEROMETERS AND G YROSCOPES There are MEMS Gyroscopes + small, interface with electronics easily - \$\$\$ Used together, accels & gyroscopes provide data to do position tracking Theres some drift Some serious number crunching needs to be done to track in real time

S ENSORS - 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)

S ENSORS – T OUCHPADS, M ICE, K EYBOARDS Lots of Multitouch interfaces Mice & Keyboards – PS2 interface

S ENSORS - O THER Alcohol Gas Barometric If you look hard enough, youll probably find what youre looking for Mic & voice recognition - SAPI Cameras & Computer Vision - OpenCV

O UTPUTS – O N /O FF 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

O UPUTS – LED S AND 7 S EGMENT LCD S 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

O UTPUTS – C HARACTER & G RAPHIC LCD S 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

O UTPUTS - P ROJECTORS Pretty much necessitates a computer, but can do cool things GRLs laser pointer graffiti

O UTPUTS – B UZZERS, P ELTIER, O THERS … 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

O UTPUT – R EGULAR DC M OTORS 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

O UTPUT – S ERVOS AND S TEPPERS 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

P ROCESSING 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)

P ROCESSING 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 isnt. 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!

P ROJECTS

Similar presentations