Top Banner
AVR
91

AVR Fundamentals

Jan 19, 2015

Download

Self Improvement

Vinit Vyas

Introduction to the AVR Family of Microcontrollers
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: AVR Fundamentals

AVR

Page 2: AVR Fundamentals

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

Page 3: AVR Fundamentals

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

Page 4: AVR Fundamentals

Processor corePeripheralsHardware Example – Polulu 3pi robotDevelopment EnvironmentsSoftware Example - PID algorithm walkthrough

Page 5: AVR Fundamentals

What is Harvard Architecture?Before we can answer that…

Page 6: AVR Fundamentals
Page 7: AVR Fundamentals
Page 8: AVR Fundamentals

Separate instruction and data pathsSimultaneous accesses to instructions & dataHardware can be optimized for access type and bus width.

Page 9: AVR Fundamentals
Page 10: AVR Fundamentals

Special instructions can access data from program space.Data memory is more expensive than program memoryDon’t waste data memory for non-volatile data

Page 11: AVR Fundamentals

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

Page 12: AVR Fundamentals

Faster clock ratesSingle cycle instructions (20 MIPS @ 20 MHz)Better compiler optimizationTypically no divide instruction in core

Page 13: AVR Fundamentals

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

Page 14: AVR Fundamentals

R0R1R3R4R5R6

R26R27R28R29R30R31

•••

7 00x00

0x01

0x02

0x03

0x04

0x05

0x1A

0x1B

0x1C

0x1D

0x1E

0x1F

addr

x register low byte

x register high byte

z register low byte

z register high byte

y register low byte

y register high byte

Page 15: AVR Fundamentals

Non-volatile program space storage16 Bit widthSome devices have separate lockable boot sectionAt least 10,000 write/erase cycles

Page 16: AVR Fundamentals

0x7FF

Application Flash0x000

ATmega 48

Application Flash

Boot Flash

0x000

ATmega 88/168/328

0x1FFF0x3FFF0x7FFF

Page 17: AVR Fundamentals

Data space storage8 Bit width

Page 18: AVR Fundamentals

32 Registers

64 I/O Registers160 External I/O

RegInternal SRAM

(512/1024/2048x8)

0x0000 – 0x001F

0x0020 – 0x005F

0x00060– 0x00FF

0x0100

0x04FF/0x6FF/0x8FF

External SRAM

Page 19: AVR Fundamentals

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

Page 20: AVR Fundamentals

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

Page 21: AVR Fundamentals

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

Page 22: AVR Fundamentals

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

Page 23: AVR Fundamentals

131 instructions Arithmetic & LogicBranchBit set/clear/testData transferMCU control

Page 24: AVR Fundamentals

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

Page 25: AVR Fundamentals
Page 26: AVR Fundamentals

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

Page 27: AVR Fundamentals

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

Page 28: AVR Fundamentals

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

Page 29: AVR Fundamentals

Power on resetExternal resetWatchdog system resetBrown out detect (BOD) reset

Page 30: AVR Fundamentals

ATmega328 has 26 reset/interrupt sources1 Reset source2 External interrupt sourcesI/O Pin state change on all 24 GPIO pinsPeripheral device events

Page 31: AVR Fundamentals

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 ...

Page 32: AVR Fundamentals

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!

Page 33: AVR Fundamentals

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

Page 34: AVR Fundamentals

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

Page 35: AVR Fundamentals

Most port pins have alternate functionsInternal peripherals use the alternate functionsEach port pin can be assigned only one function at a time

Page 36: AVR Fundamentals
Page 37: AVR Fundamentals

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)

Page 38: AVR Fundamentals

Multiple Operating modesSimple timer / counterOutput Compare Function

Waveform generatorClear/set/toggle on match

Frequency controlPulse Width Modulation (PWM)

Page 39: AVR Fundamentals

TCNTnClockSelect

OCRnA

OCRnB

Waveform

Generator

=

Waveform

Generator

=

TCCRnA

TCCRnB

Tn

OCnA

OCnB

IRQ

IRQ

DATA BUS

DATA BUS

Page 40: AVR Fundamentals

Use Clear Timer on Compare Match (CTC) ModeOCnx Toggles on Compare Match

0

TOP = OCRnx

OCnx(toggle)

Page 41: AVR Fundamentals

Dynamically change duty cycle of a waveformUsed to control motor speed

Page 42: AVR Fundamentals

Fast PWM ModeCounter counts from BOTTOM (0) to MAXCounter reset to 0 at MAXOCnx cleared at TOPOCnx set at BOTTOM

Page 43: AVR Fundamentals

MAX

BOTTOM

TOP

OCnx

Clear on TOP

Set on BOTTOM

Page 44: AVR Fundamentals

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

Page 45: AVR Fundamentals

10 Bit Successive Approximation ADC8 Channel multiplexer using port pins ADC0-7Max conversion time 260 μsec.

Page 46: AVR Fundamentals

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

Page 47: AVR Fundamentals

Industry standard serial protocol for communication between local devicesMaster/Slave protocol3 Wire interfaceSlaves addressed via Slave Select (SS) inputs

Page 48: AVR Fundamentals

SCLK Serial Clock

MOSI Master Out Slave In

MISO Master In Slave Out

SS Slave Select

Page 49: AVR Fundamentals

Industry standard serial protocol for communication between local devicesMaster/Slave protocol2 Wire interfaceByte oriented messagesSlave address embedded in command

Page 50: AVR Fundamentals

SDA Serial Data

SCL Serial Clock

Page 51: AVR Fundamentals

EEPROMIO ExpandersReal Time ClocksADC & DACTemperature sensorsUltrasonic range findersCompassServo / Motor ControllerLED Display

Page 52: AVR Fundamentals

Universal Synchronous and Asynchronous serial Receiver and TransmitterFull Duplex OperationHigh Resolution Baud Rate GeneratorCan provide serial terminal interface

Page 53: AVR Fundamentals

Some chips have JTAG interfaceIndustry standard for debugging chips in circuitConnect to special JTAG signalsCan program

FLASHEEPROMAll fusesLock bits

Page 54: AVR Fundamentals

ISP (In-System Programmer)Connect to 6 or 10 pin connectorSPI interfaceSpecial cable required

Can program FLASHEEPROMSome fusesLock bits

Page 55: AVR Fundamentals
Page 56: AVR Fundamentals
Page 57: AVR Fundamentals
Page 58: AVR Fundamentals
Page 59: AVR Fundamentals

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

Page 60: AVR Fundamentals

M

V+

V-

1

3

2

4

Page 61: AVR Fundamentals

M

V+

V-

1

3

2

4

PD5=1

PD6 (OC0A) PMW

Page 62: AVR Fundamentals

M

V+

V-

1

3

2

4PD3=1

PB3 (OC2A) PMW

Page 63: AVR Fundamentals

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

Page 64: AVR Fundamentals

1. Output: 10 μsec pulse on PC0

2. Input: measure decay

t indicates amountof reflected light

Page 65: AVR Fundamentals

ADC6: battery voltage monitorADC7: reads trimmer pot voltage

Page 66: AVR Fundamentals

Buzzer: Timer1 PB2 (OC1B)User defined (can be USART) : PD0, PD1Device (ISP) Programming: PB3, PB4, PB520 MHz crystal: PB6, PB7

Page 67: AVR Fundamentals

Choose a languageBASCOM C/C++Assembler (machine language)

Choose a platformLinuxWindows

Page 68: AVR Fundamentals

Text Editor / IDETool Chain

CompilerLibraries

Programmer (cable & software)

Page 69: AVR Fundamentals

Windows based BASIC compiler for AVR FamilyComplete IDEIncludes simulatorExtensive library for AVR peripheral controlIncludes ISP programmerDemo versions available – limited code space

Page 70: AVR Fundamentals
Page 71: AVR Fundamentals
Page 72: AVR Fundamentals

LinuxAVR-GCC

Based on GNU toolsetOpen Source AVR-LIBC libraries

WindowsWIN-AVR

Port of AVR-GCC to Windows

Page 73: AVR Fundamentals

LinuxEditors & command line toolsEclipse IDE

WindowsAtmel AVR Studio

Includes ISP programming supportEclipse IDE

Page 74: AVR Fundamentals

STK 200/300/400/500Atmel AVR starter kit and development systemInterfaces to AVR Studio

avrdudeProgramming support for all memories

Page 75: AVR Fundamentals

Win-AVRAVR-StudioProprietary libraries

Page 76: AVR Fundamentals

PID AlgorithmPID Code Walkthrough

Page 77: AVR Fundamentals

Simple Line FollowerThree sensors can provide position information

left of centeron centerright of sensors

React to current position only

Page 78: AVR Fundamentals

Three choices:

Page 79: AVR Fundamentals

Guaranteed to zig-zag back and fort h

Page 80: AVR Fundamentals

Anticipates where we want to goContinuously adjusts direction to get thereAdjustable constants control behavior

Page 81: AVR Fundamentals

P

I

D

ΣΣ ProcessSet point(center line)

Error Output+

Page 82: AVR Fundamentals

(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.

Page 83: AVR Fundamentals

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

Page 84: AVR Fundamentals

// 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

Page 85: AVR Fundamentals

// 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);

Page 86: AVR Fundamentals

// 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;

Page 87: AVR Fundamentals

// 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);

Page 88: AVR Fundamentals

Open source elections prototyping platformHardware

Based on Atmega (328 & others)Software

Wiring language, based on c++Boot loaderArduino IDE

Page 89: AVR Fundamentals

ATmega 48/88/168/328What we have been talking about

ATmega 164/324/644/1284JTAG interfaceAll 4 IO Ports A,B,C & DMore memory

Page 90: AVR Fundamentals

PDIP – Plastic Dual In-line PackageGood for hobbyists

TQFP – Thin Quad Flat PackSurface mount

MLF – MicroLeadFrame28 & 32 pinSurface mount / higher temperature

Page 91: AVR Fundamentals

www.atmel.comwww.polulu.comhttp://winavr.sourceforge.netwww.avrfreaks.netwww.wrighthobbies.netwww.eclipse.orgJust Google AVR