You are on page 1of 100

ATmega8 Microcontroller

Basic Features
II: Atmega8 – Basic features
ATmega8 - RISC Architecture

● 130 Instructions – Most Single-clock Cycle Execution


● 32 x 8 General Purpose Working Registers
● 64 x 8 Special Function Registers (I/O Registers)
● Up to 16 MIPS Throughput at 16 MHz
● On-chip 2-cycle Multiplier

Nonvolatile Program and Data Memories

● 8K Bytes of In-System Self-Programmable Flash


10,000 Write/Erase Cycles
● Optional Boot Code Section with Independent Lock Bits
● 512 Bytes EEPROM (100,000 Write/Erase Cycles)
● 1K Byte Internal SRAM
● Programming Lock for Software Security
II: Atmega8 – Basic features
Peripheral Features

● Two 8-bit Timer/Counters


● One 16-bit Timer/Counter with Capture Mode
● Real Time Counter with Separate Oscillator
● Three PWM Channels
● 6-channel ADC in PDIP package 10 Bit accuracy
(TQFP: 8 channels)
● Two-wire Serial Interface (TWI)
● Programmable Serial USART
● Master/Slave SPI Serial Interface
● Programmable Watchdog Timer with On-chip
Oscillator
● On-chip Analog Comparator
II: Atmega8 – Basic features
Special Microcontroller Features
● Power-on Reset and Programmable Brown-out Detection
● Internal Calibrated RC Oscillator
● External and Internal Interrupt Sources
● Five Sleep Modes
Idle mode: Stops the CPU while allowing SRAM, Timer/Counters, SPI port,
and interrupt system to continue functioning.

 Power down mode: Saves the register contents but freezes the Oscillator,
disabling all other chip functions until the next Interrupt or Hardware Reset.

Power-save mode: Asynchronous timer continues to run, allowing the user


to maintain a timer base while the rest of the device is sleeping.

ADC Noise Reduction mode: Stops the CPU and all I/O modules except
asynchronous timer and ADC, to minimize switching noise during ADC
conversions.

Standby mode: Crystal/resonator Oscillator is running while the rest of the


device is sleeping. This allows very fast start-up combined with low-power
consumption.
II: Atmega8 – Basic features
I/O and Packages
● 23 Programmable I/O Lines
● 28-lead PDIP and 32-lead TQFP and 32-pad MLF
(Micro Lead Frame)

Operating Voltages
● 2.7 - 5.5V (ATmega8L)
● 4.5 - 5.5V (ATmega8)

Speed Grades
● 0 - 8 MHz (ATmega8L)
● 0 - 16 MHz (ATmega8)

Power Consumption at 4 Mhz, 3V, 25°C


● Active: 3.6 mA
● Idle Mode: 1.0 mA
● Power-down Mode: 0.5 μA
II: Atmega8 – Basic features
ATmega8 Core Architecture

Mega8 CPU Core


● Seperate Instruction and
Data Memories (Harvard)
● All 32 General Purpose
Registers connected to
ALU
• Allowing two independent
registers to be accessed in
one single instruction
executed in one clock cycle
● I/O Modules connected to
Data Bus and accessible via
Special Function Registers
II: Atmega8 – Basic features
Harvard architecture

● Separate storage and signal pathways


for instructions and data.

● History: Harvard Mark I


relay-based computer

● word width, timing, and


implementation technology of
instruction and data memories
can differ.

● Contrast: ‘Von Neumann’ -


architecture: Instructions and data
use the same signal pathways and
memory.
II: Atmega8 – Basic features

Harvard architecture

● Ability to fetch the next instruction at the


same time it completes the current
instruction.

● Speed is gained at the expense of more


complex electrical circuitry.

In a computer with Harvard architecture, the CPU can read


an instruction and data from memory at the same time.
II: Atmega8 – Basic features
ATmega8 Pinout and Packages (DIP and TQFP)
II: Atmega8 – Basic features
Pin and Port Overview

GND: Ground (0V)


VCC: Digital Supply Voltage (2.7 – 5.5V)
AVCC: Analog Supply Voltage
connect to low-pass filtered VCC
AREF: Analog Reference Voltage, usually AVCC
/Reset: Low level on this pin will generate a reset

Port B, Port C, Port D:


General Purpose 8 Bit bidirectional I/O - Ports,
optional internal pullup-resistors when configured as input
output source capability: 20mA

Special Functions of the Ports available as configured using the SFRs:

Port D: USART, external Interrupts, Analog Comparator


Port B: External Oscillator/Crystal, SPI
Port C: A/D converters, TWI
II: Atmega8 – Basic features

Memory organization
II: Atmega8 – Basic features

Program Flash Memory


On-chip, In-system Reprogrammable flash
memory

8 Kbytes, organized in 4K x 16 bits (AVR


instructions are 16-bits or 32-bits wide)

At least 10,000 write/erase cycles

Program Counter (PC) = 12 bits (4K Program


memory locations)

Accessible via special instructions: Load


Program Memory (LPM), Store Program
Memory (SPM)

Boot Loader support: Boot Flash Section,


SPM can be executed only from Boot Flash
II: Atmega8 – Basic features

EEPROM - Memory:

512 Bytes, single Bytes can be read and written

Special EEPROM read and write procedure using SFRs:

EEPROM Address Register, EEPROM Data Register,


EEPROM Control Register
C – Library Functions available

Precautions to prevent EEPROM memory corruption:

● no flash memory or interrupt operations


● stable power supply
II: Atmega8 – Basic features
SRAM Data Memory:

32 GPR’s and 64 SFR’s mapped to SRAM memory space

Lower 1120 Data memory locations address the Register File, the I/O
Memory, and the internal data SRAM (First 96 locations address the
Register File and I/O Memory, Next 1024 locations address the internal
data SRAM).

SFR’s accessed via in / out instructions (I/O-registers)

1 Kbytes of internal SRAM can be accessed from address 0x060 to


0x45F

5 Direct and indirect addressing modes (Direct, Indirect with


Displacement, Indirect, Indirect with Pre-decrement, and Indirect with
Post-increment)
II: Atmega8 – Basic features
II: Atmega8 – Basic features

General Purpose Registers:

Although not being physically implemented as SRAM locations, GPR’s can be


accessed by SRAM locations

X, Y and Z 16-bit registers


can be used for indirect addressing

ALU - Input / output schemes:


one 8-bit operand, 8-bit result
two 8-bit operands, 8-bit result
two 8-bit operands, 16-bit result
one 16-bit operand, 16-bit result
II: Atmega8 – Basic features

I/O Memory (SFR) Overview


II: Atmega8 – Basic features

I/O Memory (SFR) Overview


II: Atmega8 – Basic features
Important I/O Registers:
SREG – Status Register : contains information about the result of the
most recently executed arithmetic instruction

Bit 7 – I: Global Interrupt Enable (SEI and CLI instructions)


Bit 6 – T: Bit Copy Storage (BLD (Bit Load) and BST (Bit Store))
Bit 5 – H: Half Carry Flag (BCD arithmetic)
Bit 4 – S: Sign Bit (between the Negative Flag N and the Two’s Complement Overflow Flag V)
Bit 3 – V: Two’s Complement Overflow Flag (two’s complement arithmetic)
Bit 2 – N: Negative Flag (negative result in an arithmetic or logic operation)
Bit 1 – Z: Zero Flag (zero result in an arithmetic or logic operation)
Bit 0 – C: Carry Flag (Carry in an arithmetic or logic operation.)
X-register, Y-register and Z-register:

16-bit address pointers for indirect addressing of the Data Space


II: Atmega8 – Basic features
Stack Pointer (SPH and SPL): used for storing temporary data, for
storing local variables and for storing return addresses after interrupts and
subroutine calls.

● Stack is a LIFO buffer located in SRAM


● Stack Pointer addresses the current location
● Push and pop instructions write / read from Stack
● Enter or return from subroutines / interrupt routines:
Address and Parameters transferred via Stack
II: Atmega8 – Basic features

I/O Ports
II: Atmega8 – Basic features
● General Purpose IO : Data Direction Input or Output
● Internal Pullup can be used for Input Pins
● Output driver can source 20mA current
● protection diodes to GND and VCC
• 3 I/O-Registers for each port:
Data Register (r/w): PORTB, PORTC, PORTD (read/write)
Data Direction Register (r/w): DDRB, DDRC, DDRD (read/write)
Port Input Pin Register (r): PINB, PINC, PIND (read)

x – Port; n – bit number


II: Atmega8 – Basic features
I/O Ports as General Digital IO:
DDRx: logic one - Pxn is configured as an output pin.
logic zero - Pxn is configured as an input pin.

PORTx: logic one - pin is configured as an input pin: pull-up resistor activated
logic zero – pin is configured as an output pin: pull-up resistor off
pins are tri-stated when a reset condition becomes active

PINx: port pin can be read through the PINxn Register Bit

Common to all Ports: clkI/O, Pullup disable (PUD), SLEEP


II: Atmega8 – Basic features
II: Atmega8 – Basic features

Alternate Port functions Port B


II: Atmega8 – Basic features

Alternate Port functions Port C


II: Atmega8 – Basic features

Alternate Port functions Port D


Simple Program

Write a C program to toggle LEDs which is connected to PORTB and


PORTD.3 continuously with 250 ms delay.
#define F_CPU 1000000 void LED_OFF (void)
#include <avr/io.h> {
#include <avr/interrupt.h> PORTB = 0x00;
#include <util/delay.h> PORTD = 0x00;
}
void LED_pin_config (void)
{ int main (void)
DDRB = 0xFF; // Output Port {
PORTB = 0x00;// Initially off LED_pin_config ();

DDRD = 0x08; // Output Port while(1)


PORTD = 0x00;// Initially off {
} LED_ON();
_delay_ms(250);
void LED_ON (void)
{ LED_OFF();
PORTB = 0xFF; _delay_ms(250);
PORTD = 0x08; }
} }
A reset switch is connected to RC6 and buzzer is connected to RC2.
Write a C program to off the buzzer when reset switch is press.

#define F_CPU 1000000 int main (void)


#include <avr/io.h> {
#include <avr/interrupt.h> pin_config ();
#include <util/delay.h>
while(1)
void pin_config (void) {
{
DDRC = 0x04; // Output Port (RC2) BUZZ_ON();
PORTC = 0x00;// Initially off _delay_ms(200);
}
}
void BUZZ_ON (void) }
{
PORTC = 0x04;
}
II: Atmega8 – Basic features

Timers / Counters
8-bit Timer/Counter0
Timer/Counter0 is a general purpose, single channel, 8-bit Timer/Counter
module. The main features are:
• Single Channel Counter
• Frequency Generator
• External Event Counter
• 10-bit Clock Prescaler
Associated Registers

TCCR0: this Timer Counter Control Register is used to configure the


timer

TCNT0: Timer Counter0 register is the “real” counter in the TIMER0


counter

TIMSK: Timer Interuupt Mask Register, used to activate/deactivate


interrupts related to timer

TOIE0: this bit when sets to “1” enables the OVERFLOW interrupt
Timer/Counter Control Register – TCCR0
Timer/Counter Register – TCNT0

Timer/Counter Interrupt Mask Register – TIMSK

Timer/Counter Interrupt Flag Register – TIFR


Special Function IO Register – SFIOR
Problem Statement 1:

Flash an LED every 6 ms and CPU clock frequency of 32 kHz using Timer0.

= [6 ms / (1/32kHz)] – 1 = 191

TCNT0 (Timer/Counter Register ) = 0 x 00; //Initalization


TCCR0 (Timer/Counter Control Register) = 0 x 01; // clkIO/(No prescaling)
#define F_CPU 32000
#include <avr/io.h> int main(void)
{
void pin_config() pin_config();
{ timer0_init();
// connect led to pin PC1
// loop forever
DDRC = 0x02;
while(1)
PORTC=0x00;
{
}
// check if the timer count reaches 191
if (TCNT0 >= 191)
void timer0_init()
{
{
PORTC ^= (1 << 1); // toggles the led
// set up timer with no prescaling
TCNT0 = 0; // reset counter
TCCR0 = 0x01;
}
}
// initialize counter
TCNT0 = 0x00;
}
}
Problem Statement 2:

Flash an LED every 8 ms and we have an XTAL of 16 MHz using Timer0.

= [8 ms / (1/16MHz)] – 1 = 1,27,999

TCNT0 (Timer/Counter Register ) = 0 x 00; //Initalization


TCCR0 (Timer/Counter Control Register) = 0 x 05; // clkIO/1024(from prescaler)
#define F_CPU 16000000 int main(void)
#include <avr/io.h> {
pin_config();
void pin_config() timer0_init();
{
// connect led to pin PC1 // loop forever
DDRC = 0x02; while(1)
PORTC=0x00; {
} // check if the timer count reaches 124
if (TCNT0 >= 124)
void timer0_init() {
{ PORTC ^= (1 << 1); // toggles the led
// set up timer with prescaler = 1024 TCNT0 = 0; // reset counter
TCCR0 = 0x05; }
}
// initialize counter
TCNT0 = 0x00; }

}
Problem Statement 3:

Flash an LED every 50 ms and XTAL of 16 MHz using Timer0.

255 = [Delay / (1/62.5kHz) ] – 1

 Time taken to the timer to overflow = 4.096 ms (50 ms ÷ 4.096 ms =


12.207)

 The timer has overflown 12 times to get 49.152 ms delay.

 Thus, in the 13th iteration, we need a delay of 50 – 49.152 = 0.848 ms.

 At a frequency of 62.5 kHz (prescaler = 256), each tick takes 0.016 ms.
Thus to achieve a delay of 0.848 ms, it would require 53 ticks.

 Thus, in the 13th iteration, we only allow the timer to count up to 53, and
then reset it.
TCNT0 (Timer/Counter Register ) = 0 x 00; //Initalization

TCCR0 (Timer/Counter Control Register) = 0 x 04; // clkIO/256 (from prescalar)

TIMSK (Timer/Counter Interrupt Mask) = 0x01;

TIFR (Timer/Counter Interrupt Flag Register)


#define F_CPU 16000000
#include <avr/io.h>
#include <avr/interrupt.h>

// global variable to count the number of overflows


volatile uint8_t tot_overflow;

void pin_config()
{
DDRC = 0x02; // connect led to pin PC1
PORTC=0x00; // Intilaize
}

void timer0_init()
{
TCCR0 = 0x04; // set up timer with prescaler = 256
TCNT0 = 0x00; // initialize counter
TIMSK = 0x01; // enable overflow interrupt
sei(); // enable global interrupts
tot_overflow = 0; // initialize overflow counter variable

}
// TIMER0 overflow interrupt service routine
// called whenever TCNT0 overflows
ISR(TIMER0_OVF_vect)
{
tot_overflow++; // keep a track of number of overflows
}

int main(void)
{
pin_config();
timer0_init();
while(1)
{
if (tot_overflow >= 12)
{
if (TCNT0 >= 53)
{
PORTC ^= (1 << 1); // toggles the led
TCNT0 = 0; // reset counter
tot_overflow = 0; // reset overflow counter
}
}
}

}
II: Atmega8 – Basic features

Analog Comparator
ACME : Analog Comparator Multiplexer Enable
ACD : Analog Comparator Disable
ACBG : Analog Comparator Bandgap Select
ACO : Analog Comparator Output
ACI : Analog Comparator Interrupt Flag
ACIE : Analog Comparator Interrupt Enable
ACIC : Analog Comparator Input Capture Enable
ACIS1, ACIS0 : Analog Comparator Interrupt Mode Select
 The Analog Comparator compares the input values on the positive pin
AIN0 and negative pin AIN1.

 When the voltage on the positive pin AIN0 is higher than the voltage
on the negative pin AIN1, the Analog Comparator Output, ACO, is set.

 The comparator’s output can be set to trigger the Timer/Counter1 Input


Capture function.

 In addition, the comparator can trigger a separate interrupt, exclusive


to the Analog Comparator. The user can select Interrupt triggering on
comparator output rise, fall or toggle.
Special Function IO Register – SFIOR

 When this bit is written logic one and the ADC is switched off
(ADEN in ADCSRA is zero), the ADC multiplexer selects the
negative input to the Analog Comparator.

 When this bit is written logic zero, AIN1 is applied to the


negative input of the Analog Comparator.
Analog Comparator Control and Status Register – ACSR

Bit 7 – ACD: Analog Comparator Disable


 When this bit is written logic one, the power to the Analog Comparator is switched
off. This bit can be set at any time to turn off the Analog Comparator. This will
reduce power consumption in Active and Idle mode.

 When changing the ACD bit, the Analog Comparator Interrupt must be disabled by
clearing the ACIE bit in ACSR. Otherwise an interrupt can occur when the bit is
changed.

Bit 6 – ACBG: Analog Comparator Bandgap Select


 When this bit is set, a fixed bandgap reference voltage replaces the positive input
to the Analog Comparator.

 When this bit is cleared, AIN0 is applied to the positive input of the Analog
Comparator.
Bit 5 – ACO: Analog Comparator Output
The output of the Analog Comparator is synchronized and then directly
connected to ACO. The synchronization introduces a delay of 1 - 2 clock
cycles.

Bit 4 – ACI: Analog Comparator Interrupt Flag


 This bit is set by hardware when a comparator output event triggers the
interrupt mode defined by ACIS1 and ACIS0.

 The Analog Comparator Interrupt routine is executed if the ACIE bit is set
and the I-bit in SREG is set.

 ACI is cleared by hardware when executing the corresponding interrupt


Handling Vector. Alternatively, ACI is cleared by writing a logic one to the
flag.

Bit 3 – ACIE: Analog Comparator Interrupt Enable


 When the ACIE bit is written logic one and the I-bit in the Status Register is
set, the Analog Comparator interrupt is activated.

 When written logic zero, the interrupt is disabled.


Bit 2 – ACIC: Analog Comparator Input Capture Enable
When written logic one, this bit enables the Input Capture function in
Timer/Counter1 to be triggered by the Analog Comparator.

The comparator output is in this case directly connected to the Input


Capture front-end logic, making the comparator utilize the noise canceler
and edge select features of the Timer/Counter1 Input Capture interrupt.

When written logic zero, no connection between the Analog Comparator


and the Input Capture function exists. To make the comparator trigger the
Timer/Counter1 Input Capture interrupt, the TICIE1 bit in the Timer
Interrupt Mask Register (TIMSK) must be set.

Bits 1,0 – ACIS1, ACIS0: Analog Comparator Interrupt Mode Select


These bits determine which comparator events that trigger the Analog
Comparator interrupt.
Analog Comparator Multiplexed Input
II: Atmega8 – Basic features

Serial Peripheral Interface


(SPI)
Serial Peripheral Interface (SPI) allows high-speed synchronous
data transfer between the ATmega8 and peripheral devices or
between several AVR devices.

The ATmega8 SPI includes the following features:

• Full-duplex, Three-wire Synchronous Data Transfer


• Master or Slave Operation
• LSB First or MSB First Data Transfer
• Seven Programmable Bit Rates
• End of Transmission Interrupt Flag
• Write Collision Flag Protection
• Wake-up from Idle Mode
• Double Speed (CK/2) Master SPI Mode
The system consists of two Shift Registers, and a Master clock generator.

The SPI Master initiates the communication cycle when pulling low the Slave Select
SS pin of the desired Slave.

Master and Slave prepare the data to be sent in their respective Shift Registers, and
the Master generates the required clock pulses on the SCK line to interchange data.

Data is always shifted from Master to Slave on the Master Out – Slave In, MOSI,
line, and from Slave to Master on the Master In – Slave Out, MISO, line.

After each data packet, the Master will synchronize the Slave by pulling high the
Slave Select, SS, line.
When configured as a Master:

SPI interface has no automatic control of the SS line. This must be


handled by user software before communication can start.

When this is done, writing a byte to the SPI Data Register starts the
SPI clock generator, and the hardware shifts the eight bits into the
Slave.

After shifting one byte, the SPI clock generator stops, setting the end
of Transmission Flag (SPIF). If the SPI interrupt enable bit (SPIE) in
the SPCR Register is set, an interrupt is requested.

The Master may continue to shift the next byte by writing it into
SPDR, or signal the end of packet by pulling high the Slave Select,
SS line.

The last incoming byte will be kept in the Buffer Register for later
use.
When configured as a Slave:

SPI interface will remain sleeping with MISO tri-stated as long as the
SS pin is driven high.

In this state, software may update the contents of the SPI Data
Register, SPDR, but the data will not be shifted out by incoming
clock pulses on the SCK pin until the SS pin is driven low.

As one byte has been completely shifted, the end of Transmission


Flag, SPIF is set. If the SPI interrupt enable bit, SPIE, in the SPCR
Register is set, an interrupt is requested.

The Slave may continue to place new data to be sent into SPDR
before reading the incoming data.

The last incoming byte will be kept in the Buffer Register for later
use.
SPI Control Register – SPCR

Bit 7 – SPIE: SPI Interrupt Enable


This bit causes the SPI interrupt to be executed if SPIF bit in the SPSR
Register is set and the if the global interrupt enable bit in SREG is set.

Bit 6 – SPE: SPI Enable


When the SPE bit is written to one, the SPI is enabled. This bit must be set to
enable any SPI operations.

Bit 5 – DORD: Data Order


When the DORD bit is written to one, the LSB of the data word is transmitted
first.

When the DORD bit is written to zero, the MSB of the data word is
transmitted first.
Bit 4 – MSTR: Master/Slave Select
This bit selects Master SPI mode when written to one, and Slave SPI mode
when written logic zero.

If SS is configured as an input and is driven low while MSTR is set, MSTR


will be cleared, and SPIF in SPSR will become set.

The user will then have to set MSTR to re-enable SPI Master mode.

Bit 3 – CPOL: Clock Polarity


When this bit is written to one, SCK is high when idle.

When CPOL is written to zero, SCK is low when idle.

The CPOL functionality is summarized below:


Bit 2 – CPHA: Clock Phase
The settings of the clock phase bit (CPHA) determine if data is sampled on
the leading (first) or trailing (last) edge of SCK. The CPHA functionality is
summarized below:

Bits 1, 0 – SPR1, SPR0: SPI Clock Rate Select 1 and 0


These two bits control the SCK rate of the device configured as a Master.
SPR1 and SPR0 have no effect on the Slave. The relationship between
SCK and the Oscillator Clock frequency fosc is shown in the following
table:
SPI Status Register – SPSR

Bit 7 – SPIF: SPI Interrupt Flag


When a serial transfer is complete, the SPIF Flag is set.

An interrupt is generated if SPIE in SPCR is set and global interrupts are


enabled.

If SS is an input and is driven low when the SPI is in Master mode, this will
also set the SPIF Flag.

SPIF is cleared by hardware when executing the corresponding interrupt


Handling Vector.

Alternatively, the SPIF bit is cleared by first reading the SPI Status Register
with SPIF set, then accessing the SPI Data Register (SPDR).
Bit 6 – WCOL: Write Collision Flag
The WCOL bit is set if the SPI Data Register (SPDR) is written during a
data transfer.

The WCOL bit (and the SPIF bit) are cleared by first reading the SPI Status
Register with WCOL set, and then accessing the SPI Data Register.

Bit 0 – SPI2X: Double SPI Speed Bit


When this bit is written logic one the SPI speed (SCK Frequency) will be
doubled when the SPI is in Master mode. This means that the minimum
SCK period will be 2 CPU clock periods.

When the SPI is configured as Slave, the SPI is only guaranteed to work at
fosc/4 or lower. The SPI interface on the ATmega8 is also used for Program
memory and EEPROM downloading or uploading.
SPI Data Register – SPDR

The SPI Data Register is a Read/Write Register used for data transfer
between the Register File and the SPI Shift Register. Writing to the
register initiates data transmission. Reading the register causes the Shift
Register Receive buffer to be read.

Data Modes
There are four combinations of SCK phase and polarity with respect to
serial data, which are determined by control bits CPHA and CPOL.

Data bits are shifted out and latched in on opposite edges of the SCK
signal, ensuring sufficient time for data signals to stabilize.
II: Atmega8 – Basic features

Universal Synchronous and


Asynchronous serial Receiver
and Transmitter (USART)
USART is a highly-flexible serial communication device.
The main features are:
• Full Duplex Operation (Independent Serial Receive and Transmit
Registers)
• Asynchronous or Synchronous Operation
• Master or Slave Clocked Synchronous Operation
• High Resolution Baud Rate Generator
• Supports Serial Frames with 5, 6, 7, 8, or 9 Databits and 1 or 2 Stop
Bits
• Odd or Even Parity Generation and Parity Check Supported by
Hardware
• Data OverRun Detection
• Framing Error Detection
• Noise Filtering Includes False Start Bit Detection and Digital Low
Pass Filter
• Three Separate Interrupts on TX Complete, TX Data Register
Empty and RX Complete
• Multi-processor Communication Mode
• Double Speed Asynchronous Communication Mode
External Hardware Interrupts
INT0 (PORTD2) and INT1 (PORTD3) pins

External Interrupt 1 is activated by the external pin INT1

External Interrupt 0 is activated by the external pin INT0

Set SREG I-bit and the corresponding interrupt mask in the GICR
MCU Control Register – MCUCR

Bit 3, 2 – ISC11, ISC10: Interrupt Sense Control 1 Bit 1 and Bit 0

Bit 1, 0 – ISC01, ISC00: Interrupt Sense Control 0 Bit 1 and Bit 0


General Interrupt Control Register –GICR

Bit 7 – INT1: External Interrupt Request 1 Enable


When the INT1 bit is set (one) and the I-bit in the Status Register (SREG) is
set (one), the external pin interrupt is enabled.

Bit 6 – INT0: External Interrupt Request 0 Enable


When the INT0 bit is set (one) and the I-bit in the Status Register (SREG)
is set (one), the external pin interrupt is enabled.
General Interrupt Flag Register – GIFR

Bit 7 – INTF1: External Interrupt Flag 1


When an event on the INT1 pin triggers an interrupt request, INTF1
becomes set (one).

Bit 6 – INTF0: External Interrupt Flag 0


When an event on the INT0 pin triggers an interrupt request, INTF0
becomes set (one).

The flag is cleared when the interrupt routine is executed. Alternatively, the
flag can be cleared by writing a logical one to it. This flag is always cleared
when INT1 and INT0 are configured as a level interrupt.
OPERATION 1 : A roll action is perform using the LEDs. The first LED is lit
and roll down to the last LED then back to the first LED. This operation is
done continuous.

OPERATION 2 - ALL the LEDs blink five (5) times.

#define F_CPU 16000000


#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

void pin_config()
{
DDRD = 1<<PD2; // Set PD2 as input (Using for interupt INT0)
PORTD = 1<<PD2; // Enable PD2 pull-up resistor

DDRB = 0xFF; // Output port


PORTB= 0x01;
}
//Interrupt Service Routine for INT0
ISR(INT0_vect)
{
unsigned char i, temp;

_delay_ms(100); // Software debouncing control

temp = PORTB; // Save current value on PORTB

/* This for loop blink LEDs on PORTB 5 times*/


for(i=0;i<5;i++)
{
PORTB = 0x00;
_delay_ms(100);
PORTB = 0xFF;
_delay_ms(100);
}

PORTB = temp; //Restore old value to PORTB


}
int main(void)
{
pin_config();

GICR = 1<<INT0; // Enable INT0


MCUCR = 1<<ISC01 | 1<<ISC00; // Trigger INT0 on rising edge
sei(); //Enable Global Interrupt

while(1)
{
if(PORTB >= 0x80)
PORTB = 0x01;
else
PORTB = PORTB << 1; // Shift to the left
_delay_ms(100);
}
}
USART
(Universal Synchronous / Asynchronous
Receiver / Transmitter)
USART interface
 Full Duplex Operation (Independent Serial Receive and Transmit
Registers)
 Asynchronous or Synchronous Operation
 Master or Slave Clocked Synchronous Operation
 High Resolution Baud Rate Generator
 Supports Serial Frames with 5, 6, 7, 8, or 9 Databits and 1 or 2
Stop Bits
 Odd or Even Parity Generation and Parity Check Supported by
Hardware
 Data OverRun Detection
 Framing Error Detection
 Noise Filtering Includes False Start Bit Detection and Digital Low
Pass Filter
 Three Separate Interrupts on TX Complete, TX Data Register
Empty and RX Complete
 Multi-processor Communication Mode
 Double Speed Asynchronous Communication Mode
How to set up USART:

 The first step is to set the baud rate in both, the master and the
slave. The baud rate has to be the same for both – master and
slave.
 Set the number of data bits, which needs to be sent.
 Get the buffer ready! In case of transmission (from AVR to some
other device), load it up with the data to be sent, whereas in case
of reception, save the previous data so that the new received
data can be overwritten onto it.
 Then enable the transmitter/receiver according to the desired
usage.
UDR: USART I/O Data
Register

UCSRA: USART Control


and Status Register A

UCSRB: USART Control


and Status Register B

UCSRC: USART Control


and Status Register C

UBRRL and UBRRH:


USART Baud Rate
Registers
USART Pin Configuration

 RxD: USART Receiver Pin (Pin 2, PD0)


 TxD: USART Transmit Pin (Pin 3, PD1)
 XCK: USART Clock Pin (Pin 6, PD4)

Modes of Operation

 Asynchronous Normal Mode (UBBR register)


 Asynchronous Double Speed Mode (Setting the U2X bit in UCSRA
register can double the transfer rate)
 Synchronous Mode (UMSEL = 1 in UCSRC register and XCK pin will
be used as either clock input (Slave) or clock output (Master))
Baud Rate Generation
Frame formats:

A frame refers to the entire data packet which is being sent/received


during a communication.
Setting the Number of DATA Bits : set by the UCSZ2:0, bits in
UCSRC Register

Setting Number of STOP Bits: USBS bit is available in the UCSRC


Register
Parity Bits :UPM1:0 bits in the UCSRC Register.

Even and Odd Parity:


Even parity results in even number of
1s, whereas odd parity results in odd
number of 1s.
USART I/O Data Register – UDR

USART Control and Status Register A - UCSRA

RXC: USART Receive Complete


TXC: USART Transmit Complete
UDR: USART Data Register Empty
FE: Frame Error
DOR: Data OverRun
PE: Parity Error
U2X: Double the USART speed
MPCM: Multi-processor Communication Mode
USART Control and Status Register B – UCSRB

RXCIE: RX complete interrupt enable


TXCIE: TX complete interrupt enable
UDRIE: Uart Data Register empty interrupt enable
RXEN: Receiver Enable
TXEN: Transmitter Enable
UCSZ2: Character Size
RXB8, TXB8: Bit 8 for receive and transmit
USART Control and Status Register C – UCSRC

URSEL: Register Select (1=UCSRC / 0=UBRRH)


UMSEL: USART Mode Select (0=async. mode, 1=sync. Mode)
UMP1, UMP0: Parity mode (00 = disabled, 10 = even, 11=odd)
USBS: Stop Bits: (0=1 Stop Bit, 1= 2 Stop bits)
UCSZ2,1, 0 : Character size
UCPOL : Clock Polarity (used for Synchronous mode only
Analog-to-Digital Converter
Features
 10-bit Resolution (successive approximation ADC)
 0.5 LSB Integral Non-linearity
 ±2 LSB Absolute Accuracy
 13μs - 260μs Conversion Time
 Up to 15 kSPS at Maximum Resolution
 6 Multiplexed Single Ended Input Channels
 2 Additional Multiplexed Single Ended Input Channels
 Optional Left Adjustment for ADC Result Readout
 0 - VCC ADC Input Voltage Range
 Selectable 2.56V ADC Reference Voltage
 Free Running or Single Conversion Mode
 Interrupt on ADC Conversion Complete
 Sleep Mode Noise Canceller
ADC Multiplexer Selection Register – ADMUX

Bit 7:6 – REFS1:0: Reference Selection Bits

Bit 5 – ADLAR: ADC Left Adjust Result

Write one to ADLAR to left adjust the result. Otherwise, the result is right
adjusted.
Bits 3:0 – MUX3:0: Analog Channel Selection Bits
ADC Control and Status Register A – ADCSRA

Bit 7 – ADEN: ADC Enable


Bit 6 – ADSC: ADC Start Conversion
Bit 5 – ADFR: ADC Free Running Select
Bit 4 – ADIF: ADC Interrupt Flag
Bit 3 – ADIE: ADC Interrupt Enable

Bits 2:0 –
ADPS2:0:
ADC Prescaler
Select Bits
The ADC Data Register – ADCL and ADCH
With regards to Atmega8 a few concepts to know beforehand are:
AVCC: This AVR pin supplies power to ADC. AVcc must not differ more than ± 0.3V from
Vcc

AREF: Another AVR pin which can optionally be used as an external voltage reference pin.

Voltage Resolution: This is the smallest voltage increment which can be measured. For 10
bit ADC, there can be 1024 different voltages and for 8 bit ADC, there can be 256 different
voltages.

Input voltage can be measured as: VIn [V] = (ADCH*256+ADCL) * VRef [V] / 1024 for 10
bit ADC

Input voltage can be measured as: VIn [V] = (ADCH)* VRef [V]/256 for 8 bit ADC

Hardware units like DAC (Digital to Analog converter), Comparator, SHA or S/H (Signal and
Hold), SAR (Successive approximation register) together complete AD conversion.

Most AVR microcontrollers have built in ADC which reduces cost and space for an external
ADC

Lastly, be informed that all ADC pins are connected to only one internal ADC, which means
you need to do one conversion at a time.
E.g.:- Switch ON and OFF two LED’s based on the ADC result

#define F_CPU 16000000


#include <avr/io.h>

void pin_config (void)


{

DDRD = 0xFF; // Output Port


PORTD = 0x00;// Initially off
}

void adc_int()
{

// ADEN: Set to turn on ADC


//ADPS2: ADPS2 and ADPS0 set to make division factor 32
//(1<<ADEN) | (1<<ADPS2) | (1<<ADPS0);

ADCSRA=0x85;

//ARef, Right justify and ADC5 (PC5)

ADMUX=0x05;

}
int main (void)
{
pin_config ();
adc_int();

while(1)
{
unsigned int adc_value; // Variable to hold ADC result
ADCSRA=0xC5; // Start conversion
while (ADSC==0); // wait until conversion completes;
adc_value = ADCW;//Store ADC result (ADCW means stores values of ADCL and ADCH)

if (adc_value < 512)


{
PORTD=0x40;
}
else
{
PORTD=0x80;
}
}