micro controller lecture notes

35
Introduction to the ATmega 16 Microcontroller

Upload: naresh-bopparathi

Post on 01-Oct-2015

30 views

Category:

Documents


2 download

DESCRIPTION

notes

TRANSCRIPT

  • Introduction to the ATmega 16 Microcontroller

  • STK500DevelopmentDevelopmentBoard

  • Description of STK500

    A row of eight pushbutton switches, each of which has a

    Description of STK500

    g p ,small LED lamp above it. These can be connected to the microcontrollers using the array of connectors just aboveabove.

    There is then a large white area, which is where the AVR chips to be programmed are inserted.

    Usually, a STK500 comes with a Atmega 16L chip mounted in the large socket on the right.Th t th t t i th i The green area at the top contains the programming electronics, and the connectors for power and communications.

  • Atmega 16 bit Microcontroller

  • ATmega 16MicroController

    ATmega 16

  • Atmega16 FeaturesFeatures High-performance, Low-power AVR 8-bit Microcontroller Advanced RISC Architecture 131 Powerful Instructions Most Single-clock Cycle Execution131 Powerful Instructions Most Single-clock Cycle Execution 32 x 8 General Purpose Working Registers Fully Static Operation Up to 16 MIPS Throughput at 16 MHz

    O On-chip 2-cycle Multiplier High Endurance Non-volatile Memory segments 16K Bytes of In-System Self-programmable Flash program memorymemory 512 Bytes EEPROM 1K Byte Internal SRAM Write/Erase Cycles: 10,000 Flash/100,000 EEPROM

    D t t ti 20 t 85C/100 t 25C(1) Data retention: 20 years at 85C/100 years at 25C(1) Optional Boot Code Section with Independent Lock BitsIn-System Programming by On-chip Boot ProgramTrue Read-While-Write Operationp Programming Lock for Software Security

  • complementary metaloxidesemiconductor (CMOS)

  • MemoryMemory ROM=Read Only Memory

    C ll d l til b it d t i t t i Called nonvolatile because it does not require power to retain memory RAM=Random Access memory

    Read and write Volatile=loses memory when power removedVolatile loses memory when power removed SRAM=Static RAM: retains data in flip flops DRAM=Dynamic RAM: data has to be refreshed because capacitors

    hold charge (i.e. values)Many other variations on RAM Many other variations on RAM

    Battery backed up RAM Use a small battery (calculator size) to maintain charge to RAM after

    power is removed. The power required to maintain data in a RAM chip is incredibly small

    so that this little battery can easily maintain data for years (maybe 5 under optimal conditions).

  • MemoryMemory EPROM=erasable programmable ROM

    U i l b th t hi UV li ht i t i d hi t Use a special box that shines UV light into window on chip to erase contents.

    Can take up to 30 minutes. Removing too early results in only partially erased memoryN d hi li f h No need to ever use this, a relic of the past.

    EEPROM=electrically erasable programmable ROM Uses a special programming pin (usually uses higher voltage) to erase

    then write new program.p g Development boards often setup so EEPROM does not have to be

    removed (like EPROM does) Flash ROM

    Like EEPROM but faster and cheaper Like EEPROM but faster and cheaper Limited write cycles (but in the several thousands)

  • How to use MemoryHow to use Memory RAM-this is where the program residesp g SRAM-this is your scratch pad for intermediate

    results or anything that you want to save during i ( b l i hoperation (remember you lose it when power

    goes). Its also the stack (discussed later). EEPROM EEPROM

    permanent storage of data like constants something you save during program execution you g y g p g y

    want to be used during the next run.

  • RegistersRegisters

    Register-a generic term with many meanings. AtRegister a generic term with many meanings. At the top level, its a group of bits (like a byte). I/O registers are set to configure the microcontroller

    1 =Output 0=Input

    General Purpose Registers are used to perform calculations

  • Internal Memory Map

  • Flash and EEPROM Map1 byteLine 0

    EEPROM

    In programming world, 4K does not equal 4000, it equals 4096=2^12. And we

    Line 4095

    p g g q qwould address 4096 bytes starting from zero and going up to 4095

    The Atmega16 is called so because it has 16 kB of Flash RAM,

  • Addressing

    How many bytes can I address with an 8 or 16 bit register? 8 bits=2^8=256 (0-255) 16 bits=2^16=65,536 (0-65,535)

    =refer to

    1 byteLine 0

    SRAM4Kbytes x 8Remember, everything starts with zero. So

    we have 65,536 elements that range from 0 to 65,535

    Line 40954095=0xFFF

  • Program FlowProgram Flow A special register called the program counter p g p g

    keeps track of the address in the Flash RAM to be executed.

    On each clock cycle that address is decodedOn each clock cycle, that address is decoded and the appropriate values are taken from memory and passed into the Arithmetic Logic Unit (ALU) to be processedUnit (ALU) to be processed.

    The value to be processed (operands) must come from a special set of 32 registers called h G l P R i Tthe General Purpose Registers. To access

    SRAM or I/O, they must be brought in/out of the registers.g

  • Atmega 16 Core (The Brain)G l P R i tGeneral Purpose Register (The Interface)

    Everything going in/out must touch the registersmust touch the registers

    Program Memory:

    (The Planning Center)

    ALU: Arithmetic and Logic gUnit (The Calculator) Input/Output: Eyes,

    ears, and other senses

  • Program CounterProgram Counter What element holds the address of the next line to be

    executed in program memory? The program counter

    When an interrupt or subroutine occurs the currentWhen an interrupt or subroutine occurs, the current address in the program counter is copied into SRAM. The program counter then jumps to the address of the subroutine When completed the address in SRAM cansubroutine. When completed, the address in SRAM can be restored to the program counter so that it can jump back.

    The stack pointer is a special register that contains the The stack pointer is a special register that contains the address (points to) the location in SRAM where the Program counter address is located. N t S i t ll EEPROM f Note: Some microcontrollers use EEPROM for program memory.

  • Program Counter/Stack Pointer10 FF

    Stack Point (16 bit)

    00 00Program Counter (16 bit)

    010203FE

    BD01 BE0400FF

    Restore Program counter using SP as address to retrieve value from

    Program Memory (Flash RAM)Internal Memory(Gen. Purpose Registers, I/O registers, SRAM)

    rjmp Main0x0000

    retrieve value from stack

    ldi R9, 0xFF ; (main label)

    ldi R10, 0x34

    call MySubroutine;

    0x0001

    0x0002

    0x0003 call MySubroutine;

    .more code

    0x0003

    0x000400000x0100

    0x0101Call Subroutine jumps Program

    MySubroutine:0000

    0x10FD

    0x10FE 00

    counter and stores return address in stack

    .subroutine code here

    ret ; jump back to Main loop

    0x01BD

    0x01BE

    000x10FE

    0x10FF 04Stack Pointer Initialized

  • Why the stack pointer? We want to restore a value to theWe want to restore a value to the

    program counter that we stored in SRAM, but where did we put it? The stack pointer gives us the address in SRAM where the

    0007

    Current Program Counteraddress in SRAM where the Program counter value is saved.

    If we had a subroutine or interrupt occur within another subroutine, we would shove another program

    0100About to jump herewe would shove another program

    counter value onto the stack (SRAM). The stack pointer allows us to retrace our steps, and exit out of each subroutine in the

    bou o ju p e e

    1 byteout of each subroutine in the proper order.

    The stack pointer can also be written to at any time and allows us to track address in the stack SRAM

    1 byte

    us to track address in the stack (SRAM) to do other fancy things.

    SRAM4Kbytes x 8

    0007

    Store Copy here

    10FFStack Pointer

  • Timing (the heartbeat)Timing (the heartbeat) Microprocessors uses oscillator (a quartz crystal) which

    d t t t id thcan produce a constant square wave to provide the synchronization of everything on the chip. Each rising edge of the square wave allows an operation to take place such as loading instructions executingplace such as loading instructions, executing instructions, and saving results.

    Different operations take a different amount of cycles (one period of the square wave) See Instruction set(one period of the square wave). See Instruction set summary for cycles.

    The oscillator source can be external or internal (on some chips)some chips).

    The Atmega16 can be set to have a clock frequency of 8MHz. With many of the operations taking only 1 cycle, that is approaching 8 million operations per second! Youthat is approaching 8 million operations per second! You could add the numbers from 1 to a million in .125 seconds!

  • Rising/Falling EdgeRising/Falling Edge Everything in a microcontroller happens on the y g pp

    rising or falling edge of a signal. Most components with in the microcontroller

    ll h hi h d b d f l iallow you to choose which edge but default is rising .

    The edge is the signal for a component to take in The edge is the signal for a component to take in new information and output the just processed information.

    It also allows for registers, components, etc. to be synchronized.

  • Prescale for a TimerMain Clock (1 MHz)

    Prescale=8, Divides Timer clock to 125 kHz

    Each Rising (or falling) edge of timer clock increments the timer count

    If I had only a 3 bit timer (2^3=8 positions), I would overflow at 7 (starts at 0) and wrap back to zero

  • Why the prescale is so important!Why the prescale is so important! For timers, the prescale allows me to set how fast the

    ti t d th th l ti f ti th t btimer counts and thus the resolution of time that can be measured For the fastest count, set prescale to 1 (default). The timer will

    count at the same rate as main clock and have a resolution equalcount at the same rate as main clock and have a resolution equal to the period (1/frequency) of the main clock

    What if I were using an eight bit timer (max count=255, 2^8-1). The counter would quickly fill up and overflow. I may decide to eithereither:

    Increase prescale so that it counts slower Switch over to a 16 bit timer (max count=65,535)

    Remember: Timers actually hold a count but knowing theRemember: Timers actually hold a count, but knowing the prescale and main clock, we know what that count means in time.

    Actual Time=Counts*TimerPeriodActual Time Counts TimerPeriod TimerPeriod=MainclockPeriod*prescale

  • More prescaleMore prescale

    For devices like the A/D, the prescale willFor devices like the A/D, the prescale will determine how fast you sample (if in free-running mode).

    You want to sample fast enough so that you do not alias (refer to Alias lecture).

    But you may want to not set the prescale too small (too fast sampling) because it wastes power For small systems running on battery power,

    reduction of power is criticalreduction of power is critical.

  • TimingTiming

    Most items have prescalers that pdivide the frequency of the clock down

  • I/O portsI/O ports Input and Output ports are the way the uC interfaces p p p y

    with other components. Each port contains 8 pins. Ports can be input only output only or bi directional Ports can be input only, output only, or bi-directional.

    The ATmega has all bi-directional ports. Bi-directional ports means they have the capability to be both, but you must choose one or the other at any given timemust choose one or the other at any given time. The direction of each pin is set through a special register for

    each port. Several ports have dual functionality With the proper Several ports have dual functionality. With the proper

    register setting, they can be used for special operations such as A/D, external interrupts, SPI, etc.

  • I/O ports Inputs

    External connections determine pin voltage Outputs

    Microcontroller sets pin voltageMicrocontroller sets pin voltage

    Controlled by three corresponding registers(memory locations) Directionset by Data Direction Register (DDRx) bi-dir.

    1 =Output 1 =Output 0=Input

    Pins are set to be inputson reset

    Data Register (PORTx)Data Register (PORTx) As an output, write signal here Writing to PORTxwhen a pin is configured as an input turns on internal pull upresistor

    (will read as logic 1 until pulled low)

    Port input pins (PINx) Note: read only

  • Serial communicationSerial communication USART=Universal Synchronous and Asynchronous y y

    serial Receiver and Transmitter Serial communication Communicate serially back to a PCy

    SPI=Serial Peripheral Interface Allows us to communicate to other devices using serial data.

    The SPI controls allow us to enable certain devices, send andThe SPI controls allow us to enable certain devices, send and receive serial data.

    Examples of things you might control with SPI: Other microprocessors, external memory, A/D, LCD display, other specialized chips.

    Advantage of using SPI is that you can control a device with a single pin as opposed to connecting in parallel (using 8 pins to send 8 bits)send 8 bits).

  • A/D and D/AA/D and D/A Analog to Digital Converter

    C t l i t i l (t i ll 0 t 5 lt ) t di it l (bi ) Converts analog input signals (typically 0 to 5 volts) to a digital (binary) representation that the mP can use.

    The Atmega128 has a 10 bit A/D. That means it can represent our analog voltage with a 10 bit number. So what is our resolution?R l i l /2^10 0 0049 l Resolution=5 volts/2^10=0.0049 volts

    Digital to Analog Converter Allows the mP to specify a voltage with a binary number and then output

    that analog voltage (like 3.25 volts)g g ( ) Atmega 128 doesnt have one and most mP dont. Most often, we create an analog voltage by using pulse width

    modulation (PWM).

    Well learn more about the specific operation of A/D and D/A later in the course

  • TimersTimers

    Timers are really just countersTimers are really just counters A register that counts (up or down depending on

    settings) The time runs using the main system clock and a

    prescaler. A prescaler divides the main system clock. Each of the four timers in the Atmega128 has its ownEach of the four timers in the Atmega128 has its own prescaler.

    So, if the system clock runs at 1 MHz, and I set the prescaler to 1024, then my clock frequency will be ~1 kHz. In other words, I get 1 count every ~.001 seconds.seconds.

  • Pulse Width ModulationPulse Width Modulation Pulse Width Modulation

    A method by which devices can be sent a voltage that is equivalent to an analog voltage

    If I have a device that I want to give 2.5 volts, I could use and D/A or I could use a 5 volt PWM signal with a 50% duty cycleD/A or I could use a 5 volt PWM signal with a 50% duty cycle.

    The effective voltage seen by the device is equal to the peak value * the duty cycle (0-1)

    Veffective=5 volts*.5=2.5 volts The key is that the frequency of the PWM wave must be faster

    than the device can respond too. If I have a small motor, and I suddenly step the voltage to 5 volts

    and record the time it takes to come to steady state speed. And I yfind that it takes .1 seconds to reach 63% of the steady state value, this is called one time constant (1-e-1). Then, following a good rule of thumb, I should make my PWM frequency at least 10 time faster than it can react. .1 second=10 hz100 Hz (minimum)

  • PWMPWM

  • Atmega 16 Circuit Diagram

  • Status RegisterStatus Register Bit 7 I: Global Interrupt Enable

    Must set this to enable interruptsp

    Bit 6 T: Bit Copy Storage Bit 5 H: Half Carry Flag Bit 4 S: Sign Bit, S = N V Bit 3 V: Twos Complement Overflow Flag Bit 3 V: Twos Complement Overflow Flag Bit 2 N: Negative Flag Bit 1 Z: Zero Flag Bit 0 C: Carry Flag

  • InterruptsInterrupts Interrupts are similar to subroutines except that you dont call

    interrupts they happen whenever a particular event happensinterrupts, they happen whenever a particular event happens. Internal interrupts are generated from several sources like

    timer/counters. I could set up a counter to interrupt when it reaches a certain value. When it interrupts, the main program would stop

    d th i t t ti ld b t d Aft l ti thand the interrupt routine would be executed. After completion, the reti command (return from interrupt) would load our return location into the program counter where it was stored from the stack.

    External interrupts have a similar operation except that their source p p pis from pins on the mP. I could set an interrupt to occur when a certain pin on the chip went high.

    You must set the Global Interrupt Enable in the SREG register to allow interrupts This is easily done with the sei command Furtherallow interrupts. This is easily done with the sei command. Further, you usually will need to clear the GIE when executing an interrupt. Why? Because you dont want another interrupt to interrupt you while executing the first interupts code. Clearing GIE is done with the clithe cli.