Al Rossetti
Modified Harvard architecture 8-bit RISC single chip microcontrollerComplete System-on-a-chip
On Board Memory (FLASH, SRAM & EEPROM)On Board Peripherals
Advanced (for 8 bit processors) technologyDeveloped by Atmel in 1996First In-house CPU design by Atmel
8 Bit tinyAVRSmall package – as small as 6 pins
8 Bit megaAVRWide variety of configurations and packages
8 / 16 Bit AVR XMEGASecond Generation Technology
32 Bit AVR UC3Higher computational throughput
Processor corePeripheralsHardware Example – Polulu 3pi robotDevelopment EnvironmentsSoftware Example - PID algorithm walkthrough
What is Harvard Architecture?Before we can answer that…
Separate instruction and data pathsSimultaneous accesses to instructions & dataHardware can be optimized for access type and bus width.
Special instructions can access data from program space.Data memory is more expensive than program memoryDon’t waste data memory for non-volatile data
Reduced Instruction Set ComputerAs compared to Complex Instruction Set Computers, i.e. x86Assumption: Simpler instructions execute fasterOptimized most used instructionsOther RISC machines: ARM, PowerPC, SPARCBecame popular in mid 1990s
Faster clock ratesSingle cycle instructions (20 MIPS @ 20 MHz)Better compiler optimizationTypically no divide instruction in core
32 8 Bit registersMapped to address 0-31 in data spaceMost instructions can access any register and complete in one cycleLast 3 register pairs can be used as 3 16 bit index registers32 bit stack pointer
R0R1R3R4R5R6
R26R27R28R29R30R31
•••
7 00x000x010x020x030x040x05
0x1A0x1B0x1C0x1D0x1E0x1F
addr
x register low bytex register high byte
z register low bytez register high byte
y register low bytey register high byte
Non-volatile program space storage16 Bit widthSome devices have separate lockable boot sectionAt least 10,000 write/erase cycles
0x7FF
Application Flash0x000
ATmega 48
Application Flash
Boot Flash
0x000
ATmega 88/168/328
0x1FFF0x3FFF0x7FFF
Data space storage8 Bit width
32 Registers64 I/O Registers160 External I/O
RegInternal SRAM
(512/1024/2048x8)
0x0000 – 0x001F
0x0020 – 0x005F
0x00060– 0x00FF
0x0100
0x04FF/0x6FF/0x8FF
External SRAM
Electrically Erasable Programmable Read Only Memory8 bit widthRequires special write sequenceNon-volatile storage for program specific data, constants, etc.At least 100,000 write/erase cycles
DEVICE FLASH EEPROM SRAMATmega48A 4K Bytes 256 Bytes 512 Bytes
ATmega48PA 4K Bytes 256 Bytes 512 Bytes
ATmega88A 8K Bytes 512 Bytes 1K Bytes
ATmega88PA 8K Bytes 512 Bytes 1K Bytes
ATmega168A 16K Bytes 512 Bytes 1K Bytes
ATmega168PA 16K Bytes 512 Bytes 1K Bytes
ATmega328 32K Bytes 1K Bytes 2K Bytes
ATmega328P 32K Bytes 1K Bytes 2K Bytes
I/O registers visible in data spaceI/O can be accessed using same instructions as dataCompilers can treat I/O space as data access
Bit manipulation instructionsSet/Clear single I/O bitsOnly work on lower memory addresses
Directly connected to all 32 general purpose registersOperations between registers executed within a single clock cycleSupports arithmetic, logic and bit functionsOn-chip 2-cycle Multiplier
131 instructions Arithmetic & LogicBranchBit set/clear/testData transferMCU control
Register ↔ register in 1 cycleRegister ↔ memory in 2 cyclesBranch instruction 1-2 cyclesSubroutine call & return 3-5 cyclesSome operations may take longer for external memory
Clock control module generates clocks for memory and IO devicesMultiple internal clock sourcesProvisions for external crystal clock source (max 20 MHz)Default is internal RC 8 MHz oscillator with ÷ 8 prescale yielding 1 MHz CPU clockDefault is only 5-10% accurate
System Clock
Prescaler
Timer/CounterOscillator
Crystal Oscillator
External Clock
Low Freq Crystal
Oscillator
Calibrated RC Oscillator
ClockMux
AVRClock
Control
FLASH & EEPROM
RAM
CPU Core
ADC
IO Modules
Timer/Counters
÷ 8
Multiple power down modesPower down mode
Wake on external reset or watchdog resetPower save mode
Wake on timer eventsSeveral standby modes
Unused modules can be shut down
Power on resetExternal resetWatchdog system resetBrown out detect (BOD) reset
ATmega328 has 26 reset/interrupt sources1 Reset source2 External interrupt sourcesI/O Pin state change on all 24 GPIO pinsPeripheral device events
Each vector is a 2 word jump instructionVectors start at program memory address 0Reset vector is at address 0Sample vector table:Address Labels Code Comments0x0000 jmp RESET ; Reset Handler0x0002 jmp EXT_INT0 ; IRQ0 Handler0x0004 jmp EXT_INT1 ; IRQ1 Handler0x0006 jmp PCINT0 ; PCINT0 Handler0x0008 jmp PCINT1 ; PCINT1 Handler ...
Fuses configure system parametersClock selection and optionsBoot optionsSome IO pin configurationsReset options
Three 8 bit fuse registersUse caution! Some configurations can put the device in an unusable state!
23 General Purpose IO BitsTwo 8 bit & one 16 bit timer/countersReal time counter with separate oscillator6 PWM Channels6 or 8 ADC channels (depends on package)Serial USARTSPI & I2C Serial InterfacesAnalog comparatorProgrammable watchdog timer
Three 8 Bit IO PortsPort B, Port C & Port DPins identified as PBx, PCx or PDx (x=0..7)
Each pin can be configured as:Input with internal pull-upInput with no pull-upOutput lowOutput high
Most port pins have alternate functionsInternal peripherals use the alternate functionsEach port pin can be assigned only one function at a time
8/16 Bit registerIncrements or decrements on every clock cycleCan be read on data busOutput feeds waveform generator
Clock SourcesInternal from clock prescalerExternal Tn Pin (Uses 1 port pin)
Multiple Operating modesSimple timer / counterOutput Compare Function
Waveform generatorClear/set/toggle on match
Frequency controlPulse Width Modulation (PWM)
TCNTnClockSelect
OCRnA
OCRnB
Waveform
Generator
=
Waveform
Generator
=
TCCRnA
TCCRnB
Tn
OCnA
OCnB
IRQ
IRQ
DATA BUS
DATA BUS
Use Clear Timer on Compare Match (CTC) ModeOCnx Toggles on Compare Match
0
TOP = OCRnx
OCnx(toggle)
Dynamically change duty cycle of a waveformUsed to control motor speed
Fast PWM ModeCounter counts from BOTTOM (0) to MAXCounter reset to 0 at MAXOCnx cleared at TOPOCnx set at BOTTOM
MAX
BOTTOM
TOP
OCnx
Clear on TOP
Set on BOTTOM
Timer 1 has capture modeCapture can be triggered by ICP1 pin or ACO from analog comparatorCapture event copies timer into input capture register ICR1Can be used to time external events or measure pulse widthsRange finders generate pulse width proportional to distance
10 Bit Successive Approximation ADC8 Channel multiplexer using port pins ADC0-7Max conversion time 260 μsec.
Compares voltage between pins AIN0 and AIN1Asserts AC0 when AIN0 > AIN1AC0 can trigger timer capture function
Range finders indicate distance with pulse withTimer capture mode can compute pulse width
Industry standard serial protocol for communication between local devicesMaster/Slave protocol3 Wire interfaceSlaves addressed via Slave Select (SS) inputs
SCLK Serial Clock
MOSI Master Out Slave In
MISO Master In Slave Out
SS Slave Select
Industry standard serial protocol for communication between local devicesMaster/Slave protocol2 Wire interfaceByte oriented messagesSlave address embedded in command
SDA Serial Data
SCL Serial Clock
EEPROMIO ExpandersReal Time ClocksADC & DACTemperature sensorsUltrasonic range findersCompassServo / Motor ControllerLED Display
Universal Synchronous and Asynchronous serial Receiver and TransmitterFull Duplex OperationHigh Resolution Baud Rate GeneratorCan provide serial terminal interface
Some chips have JTAG interfaceIndustry standard for debugging chips in circuitConnect to special JTAG signalsCan program
FLASHEEPROMAll fusesLock bits
ISP (In-System Programmer)Connect to 6 or 10 pin connectorSPI interfaceSpecial cable required
Can program FLASHEEPROMSome fusesLock bits
CW: PD5 & PD6 PWM mode (OC0B, OC0A)CCW: PD3 & PB3 PWM mode (OC2B, OC2A)Motor interface uses H-Bridge controllerSpeed and direction controlled by port bitsController standby controlled by PC6
M
V+
V-
1
3
2
4
M
V+
V-
1
3
2
4
PD5=1
PD6 (OC0A) PMW
M
V+
V-
1
3
2
4PD3=1
PB3 (OC2A) PMW
PC5 enables the IR emittersOne port pin for each of 5 sensors, PC0-4Port pin used as input and output
Set pin as output high for 10 μsec to charge RC circuitSet pin as inputMeasure time for voltage to drop (using TCNT2)Time indicates level of light
1. Output: 10 μsec pulse on PC0
2. Input: measure decay
t indicates amountof reflected light
ADC6: battery voltage monitorADC7: reads trimmer pot voltage
Buzzer: Timer1 PB2 (OC1B)User defined (can be USART) : PD0, PD1Device (ISP) Programming: PB3, PB4, PB520 MHz crystal: PB6, PB7
Choose a languageBASCOM C/C++Assembler (machine language)
Choose a platformLinuxWindows
Text Editor / IDETool Chain
CompilerLibraries
Programmer (cable & software)
Windows based BASIC compiler for AVR FamilyComplete IDEIncludes simulatorExtensive library for AVR peripheral controlIncludes ISP programmerDemo versions available – limited code space
LinuxAVR-GCC
Based on GNU toolsetOpen Source AVR-LIBC libraries
WindowsWIN-AVR
Port of AVR-GCC to Windows
LinuxEditors & command line toolsEclipse IDE
WindowsAtmel AVR Studio
Includes ISP programming supportEclipse IDE
STK 200/300/400/500Atmel AVR starter kit and development systemInterfaces to AVR Studio
avrdudeProgramming support for all memories
Win-AVRAVR-StudioProprietary libraries
PID AlgorithmPID Code Walkthrough
Simple Line FollowerThree sensors can provide position information
left of centeron centerright of sensors
React to current position only
Three choices:
Guaranteed to zig-zag back and fort h
Anticipates where we want to goContinuously adjusts direction to get thereAdjustable constants control behavior
P
I
D
ΣΣ ProcessSet point(center line)
Error Output+
–
(P) ProportionalWhere we are relative to where we want to be.
(I) IntegralSum of previous errors. History of where we were.
(D) DerivativeRate of change. Affects how fast we react to changes.
Useful functionsread_line
Returns a value between 0 – 40000 – 1000: robot is far right of line1000 – 3000: robot is approximately centered3000 – 4000: robot is far left of line
set_motorsSet speed and direction of both motors
-255 – 0 : reverse direction0 – 255: forward direction
// Introductory messages. The "PROGMEM" identifier causes the data to// go into program space.const char welcome_line1[] PROGMEM = " Pololu";const char welcome_line2[] PROGMEM = "3\xf7 Robot";const char demo_name_line1[] PROGMEM = "PID Line";const char demo_name_line2[] PROGMEM = "Follower";
// A couple of simple tunes, stored in program space.const char welcome[] PROGMEM = ">g32>>c32";const char go[] PROGMEM = "L16 cdegreg4";A
// Auto-calibration: turn right and left while calibrating the// sensors.for(counter=0;counter<80;counter++){
if(counter < 20 || counter >= 60)set_motors(40,-40);
elseset_motors(-40,40);
// This function records a set of sensor readings and keeps// track of the minimum and maximum values encountered. The// IR_EMITTERS_ON argument means that the IR LEDs will be// turned on during the reading, which is usually what you// want.calibrate_line_sensors(IR_EMITTERS_ON);
// Since our counter runs to 80, the total delay will be// 80*20 = 1600 ms.delay_ms(20);
}set_motors(0,0);
// Get the position of the line. Note that we *must* provide// the "sensors" argument to read_line() here, even though we// are not interested in the individual sensor readings.unsigned int position = read_line(sensors,IR_EMITTERS_ON);// The "proportional" term should be 0 when we are on the line.int proportional = ((int)position) - 2000;
// Compute the derivative (change) and integral (sum) of the position.int derivative = proportional - last_proportional;integral += proportional;
// Remember the last position.last_proportional = proportional;
// Compute the difference between the two motor power settings,// m1 - m2. If this is a positive number the robot will turn// to the right. If it is a negative number, the robot will// turn to the left, and the magnitude of the number determines// the sharpness of the turn.int power_difference = proportional/20 + integral/12000 + derivative*7/4;
// Compute the actual motor settings. We never set either motor// to a negative value.const int max = 250;if(power_difference > max)
power_difference = max;if(power_difference < -max)
power_difference = -max;
// One Motor will always be full speed
if(power_difference < 0)set_motors(max+power_difference, max);
elseset_motors(max, max-power_difference);
Open source elections prototyping platformHardware
Based on Atmega (328 & others)Software
Wiring language, based on c++Boot loaderArduino IDE
ATmega 48/88/168/328What we have been talking about
ATmega 164/324/644/1284JTAG interfaceAll 4 IO Ports A,B,C & DMore memory
PDIP – Plastic Dual In-line PackageGood for hobbyists
TQFP – Thin Quad Flat PackSurface mount
MLF – MicroLeadFrame28 & 32 pinSurface mount / higher temperature
www.atmel.comwww.polulu.comhttp://winavr.sourceforge.netwww.avrfreaks.netwww.wrighthobbies.netwww.eclipse.orgJust Google AVR