Вы находитесь на странице: 1из 58

Department of Electronic Engineering

Faculty of Engineering & Technology


International Islamic University, Islamabad

Microcontroller Based
System Design
Prepared By: Engr. Muhammad Muzammil
Revised on: 27th August, 2013

Name:
Reg No.
Section:
Microcontroller Based System Design

LIST OF EXPERIMENTS

S. # Title Page #
1. I/O Ports Programming & LED Interfacing 2

2. Seven Segment Display Interfacing 5

3. Timer and Counter Programming 8

4. Interrupt Programming 14

5. Serial Port Interfacing and Programming 19

6. LCD Interfacing 25

7. ADC Programming 29

8. PWM Programming 34

9. SPI Programming 39

10. I2C or TWI Programming 44

11. Servo Motor Interfacing 51

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 1
Microcontroller Based System Design

Lab No. 1 - I/O Ports Programming & LED Interfacing


Objectives:
 To familiarize the student with the basic operation of the Arduino Uno board, and
Integrated Development Environment (IDE). By the end of the exercise, the student
should be able to know the basic functionalities of the IDE.
 To understand that how to make a port input or output
 First C Program to blink LEDs

Arduino Overview:
Arduino is a prototype platform (open-source) based on an easy-to-use hardware and
software. It consists of a circuit board, which can be programed (referred to as a
microcontroller) and a ready-made software called Arduino IDE (Integrated
Development Environment), which is used to write and upload the computer code to the
physical board.
The key features are:
 Arduino boards are able to read analog or digital input signals from different
sensors and turn it into an output such as activating a motor, turning LED on/off,
connect to the cloud and many other actions.
 You can control your board functions by sending a set of instructions to the
microcontroller on the board via Arduino IDE (referred to as uploading software).
Unlike most previous programmable circuit boards, Arduino does not need an
extra piece of hardware (called a programmer) in order to load a new code onto
the board. You can simply use a USB cable.
 Additionally, the Arduino IDE uses a simplified version of C++, making it easier
to learn to program.
 Finally, Arduino provides a standard form factor that breaks the functions of the
micro-controller into a more accessible package

Arduino UNO Component View:


 Analog input pins – pins (A0-A5) that take-in analog values to be converted to
be represented with a number range 0-1023 through an Analog to Digital
Converter (ADC).
 ATmega328 chip – 8-bit microcontroller that processes the sketch you
programmed.
 Built-in LED – in order to gain access or control of this pin, you have to change
the configuration of pin 13 where it is connected to.
 Crystal Oscillator – clock that has a frequency of 16MHz
 DC Jack – where the power source (AC-to-DC adapter or battery) should be
connected. It is limited to input values between 6-20V but recommended to be
around 7-12V.

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 2
Microcontroller Based System Design

 Digital I/O pins – input and output pins (0-13) of which 6 of them (3, 5, 6, 9, 10
and 11) also provide PWM (Pulse Width Modulated) output by using the
analogWrite() function. Pins (0 (RX) and 1 (TX)) are also used to transmit and
receive serial data.

 ICSP Header – pins for “In-Circuit Serial Programming” which is another method
of programming.

 ON indicator – LED that lights up when the board is connected to a power


source.

 Power Pins – pins that can be used to supply a circuit with values VIN (voltage
from DC Jack), 3.3V and 5V.

 Reset Button – a button that is pressed whenever you need to restart the
sketch programmed in the board.

 USB port – allows the user to connect with a USB cable the board to a PC to
upload sketches or provide a voltage supply to the board. This is also used for
serial communication through the serial monitor from the Arduino software.

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 3
Microcontroller Based System Design

Arduino Program Structure:


Arduino programs (also called sketches) can be divided in three main parts: Structure,
Values (variables and constants), and Functions. In this session, we will learn about
the Arduino software program, step by step, and how we can write the program without
any syntax or compilation error.

Let us start with the Structure. Software structure consist of two main functions:

 void Setup( ) function


 void Loop( ) function

void setup ( )

 The setup() function is called when a sketch starts. Use it to initialize the
variables, pin modes, start using libraries, etc. The setup function will only run
once, after each power up or reset of the Arduino board.

void loop ( )

 After creating a setup() function, which initializes and sets the initial values, the
loop() function does precisely what its name suggests, and loops consecutively,
allowing your program to change and respond. Use it to actively control the
Arduino board

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 4
Microcontroller Based System Design

First Arduino Sketch:


Statement:

Write a program to toggle LEDs connected to Port B with delay of one second

Void setup( )

DDRB= 0xFF;

Void loop( )

PORTB = 0xFF;

delay(1000);

PORTB =0x00;

delay(1000);

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 5
Microcontroller Based System Design

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 6
Microcontroller Based System Design

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 7
Microcontroller Based System Design

Lab No. 2 - Seven Segment Display Interfacing


Objectives:
 7 segment display interfacing and programming
 To understand the multiplexing technique

Introduction:

A seven segment display, as its name indicates, is composed of seven elements. Individually on
or off, they can be combined to produce simplified representations of the numerals. A single
LED is used inside one segment to radiate light through it.

If cathodes of all the LEDs are common, this type of display is called common cathode and for
common anode type display, anode of all LEDs are common and connected to the common pin.

Multiplexing:
Multiplexing is required when we want to interface more than one displays with microcontroller.
If we interface them normally, they will require lots of I/O ports. In multiplexing, only one display
is kept active at a time but we see all of them active. For multiplexing all the displays are
connected in parallel such that if you activate any segment, say ‘a’ the ‘a’ segment of all
displays glows up. But we can switch ON and OFF the “common” line of the displays with the
Microcontroller pins. So if we wish to light up the ‘a’ segment of display 1 we simply switch on
display 2 first by applying ground level (for common cathode display) at the common pin of the
display and then send a high signal on the I/O pin connected to segment ‘a’ to lit it.

C Code for two digit 7 segment display:


#include<AVR/io.h>
#include<util/delay.h>

// PORTA.0 = b PORTA.1 = a PORTA.2 = f


// PORTA.3 = g PORTA.4 = dot PORTA.5 = c
// PORTA.6 = d PORTA.7 = e

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 8
Microcontroller Based System Design

// a
// _____
// f | g | b
// |_____|
// e | | c dot
// |_____| .
// d
//________________________________________
// | No. | e d c dot g f a b |
// | 0 | 1 1 1 0 0 1 1 1 = 0xE7 |
// | 1 | 0 0 1 0 0 0 0 1 = 0x21 |
// | 2 | 1 1 0 0 1 0 1 1 = 0xCB |
// | 3 | 0 1 1 0 1 0 1 1 = 0x6B |
// | 4 | 0 0 1 0 1 1 0 1 = 0x2D |
// | 5 | 0 1 1 0 1 1 1 0 = 0x6E |
// | 6 | 1 1 1 0 1 1 1 0 = 0xEE |
// | 7 | 0 0 1 0 0 0 1 1 = 0x23 |
// | 8 | 1 1 1 0 1 1 1 1 = 0xEF |
// | 9 | 0 1 1 0 1 1 1 1 = 0x6F |

void Display(unsigned char); //Function prototype declaration


unsigned char SevenSegment[]= { 0xE7, 0x21, 0xCB, 0x6B, 0x2D, 0x6E,
0xEE, 0x23, 0xEF, 0x6F};
void main(void)
{
DDRA = 0xFF; // Port A as output
DDRB = 0xFF; // Port B as output
unsigned char i = 0;
while(1)
{
Display(i); // Displays two digit value on 7 segments
i++;
if(i > 99)
i = 0;
}
return 0;
}

void Display(unsigned char n)


{
unsigned char units, tens, x;
{
tens = n/10; // Separate tens from a two digit number
units = n%10; // Separate units from a two digit number
for(x = 0; x<1100; x++) // Generate delay of about 1 second
{
PORTB = 0xFE; // Select one display to show units value
PORTA = Seven_Segment[units]; // Display units
_delay_us(500);

PORTB = 0xFD; // Select second display to show tens value


PORTA = Seven_Segment[tens]; // Display tens
_delay_us(500);
}
}

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 9
Microcontroller Based System Design

Simulation:

Home Task:
Extend the above circuit to four 7-segment displays. Value of least significant 7 segment
display is incremented after every 125 milliseconds (approx).

Attach three push buttons with three MSBs of PortB. When Switch 1 (PortB.7) is
pressed, counting stops and current value is retained on the 7-segment displays
constantly. Now by pressing Switch 2 (PortB.6), value displayed on 7-segment displays
is incremented and by pressing switch 3 (PortB.5), value on 7-segment displays is
decremented. Now again by pressing Switch 1, counting is started from the
new/changed value on 7-segment displays.

Note: Define, declare and use the functions, UpCount(), DownCount(), SetCount() in
your code.

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 10
Microcontroller Based System Design

Lab No. 3 – Timer and Counter Programming


Objectives:
 To understand the modes and functionality of timers of ATmega16
 To program Timer0 to generate a square waves
 To program Timer1 for event counting

Introduction:
Atmega16 has three timers. Timer 0 and Timer 2 are 8-bit timers whereas Timer 1 is the 16-bit
timer. Generally, a timer can be used in two modes i.e. Timer and Counter. If we use internal
clock source, then the frequency of the oscillator is fed to the timer. In this configuration, timer
can be used to generate the time delay. If we use the external clock option, we feed pulses
through one of the I/O pins. In this configuration, timer can be used as event counter.

Important Registers and Flags Associated with Timers:


Each timer has following registers associated with it:
TCNTn: Timer/Counter Reg: Upon reset, it has zero value and counts up with each timer clock
TCCRn: Timer/Counter Control Reg: For setting modes of operation of Timer n
OCRn: Output Compare Reg: When contents of TCNT are equal to OCR, OCF flag is raised
and value of TCNTn is reset to zero
TOVn: Timer Overflow Flag: When overflow occurs, this flag is raised
OCFn: Output Compare Flag: Discussed in OCRn

There are four modes of operation. Each timer can be programmed to any one mode out of four
available modes options using timer mode selector bit i.e. WGM00 and WGM01 bits for timer0.
Following are the timer modes:

1. Normal Mode:
In this mode, timer can be used for delay generation. Timer starts counting from the
initial value of TCNT0 up to the maximum value at every crystal clock (if no prescaler is
used). After the maximum value, TCNT0 register is reset to value 0x00.

Normal mode of timer 0

2. CTC (Clear Timer on Capture match) Mode:


In CTC mode the counter is cleared to zero when the counter value (TCNT0) matches
the OCR0. The OCR0 defines the top value for the counter.

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 11
Microcontroller Based System Design

CTC mode of timer 0

3. PWM, phase correct Mode


4. Fast PWM Mode

Mode 3 and 4 will be discussed in the PWM lab.

a) TIMER 0 PROGRAMMING FOR SQUARE WAVE GENERATION:


Bit # 7 6 5 4 3 2 1 0
Bit Name FOC0 WGM00 COM01 COM00 WGM01 CS02 CS01 CS00
Read/Write W RW RW RW RW RW RW RW
Initial Value 0 0 0 0 0 0 0 0

FOC0 Force Output Compare: FOC0 bit is only active when the WGM00:1
bits specifies a non-PWM mode. This bit is always read as zero. When
this bit is set, and a compare with
WGM00 WGM01 Timer Mode 0 Selector Bits (Four modes available)
0 0 Normal Mode
0 1 CTC (Clear Timer on Compare Match) Mode
1 0 PWM, Phase Correct Mode
1 1 Fast PWM
COM01 : COM00 Compare Output Mode: These bits control waveform generation, if
CTC mode is selected through WGM00-01 bits then:
0 0 Normal mode operation
0 1 Toggle OC0 (PB3, Pin 4) on compare match
1 0 Clear OC0 on compare match
1 1 Set OC0 on compare match
CS02:00 D2 D1 D0 Timer 0 Clock Source Selector
0 0 0 No clock source (Timer/Counter stopped)
0 0 1 clk (No Prescaling)
0 1 0 clk / 8
0 1 1 clk / 64
1 0 0 clk / 256
1 0 1 clk / 1024
1 1 0 External clock on T0 (PB0) pin. Clock on falling edge
1 1 1 External clock on T0 (PB0) pin. Clock on rising edge

TCCR0 (Timer / Counter Control Register)

Bit # 7 6 5 4 3 2 1 0
Bit Name OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0
Read/Write W RW RW RW RW RW RW RW
Initial Value 0 0 0 0 0 0 0 0

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 12
Microcontroller Based System Design

TOV0 D0 Timer 0 overflow flag bit (0 = Timer0 did not overflow)


OCF0 D1 Timer 0 output compare flag (0 = compare match did not occur)
TOV1 D2 Timer 1 overflow flag bit
OCF1B D3 Timer 1 output compare B match flag
OCF1A D4 Timer 1 output compare A match flag
ICF1 D5 Input capture flag
TOV2 D6 Timer 2 overflow flag
OCF2 D7 Timer 2 output compare flag
TIFR(Timer / Counter Interrupt Flag Register)

Steps to Program 8-Bit, Timer 0 in Normal Mode:


1. Load TCNT0 register with initial values from which the timer will count up.
2. Load TCCR0 register according to the operation required (Mode selection, prescaler
setting etc.)
3. Keep monitoring TOV0 flag in TIFR register. If TOV0 flag is raised, timer overflow occurs.
Now clear TOV0 flag and proceed to step 1 again.
4.

Difference between Timer0 and Timer2:


1. Both the timers are 8-bit timers but first difference is that Timer2 can also be used as Real
Time Clock (RTC) when a crystal of 32.768 kHz is connected between TOSC1 and
TOSC2 pins and AS2 bit of ASSR (Asynchronous Status Reg.) is set.
2. Last two combinations of CS02-00 bits select the rising and falling edge of external event
counter in Timer0. Whereas in Timer2 these two combinations of CS22-20 bits used to
select different options of prescaler.
3. Timer2 cannot be used as an event counter.

b) TIMER 1 PROGRAMMING FOR EVENT COUNTER:


Timer0 and timer1 can also be programmed to count the pulses or events (falling edge or rising
edge) T0 and T1 (PB0 and PB1) pins respectively.

Following steps are undertaken to program the timer1 as 16-bit event counter on T1. Before
programming Timer1, read all the registers of Timer1 thoroughly.

Steps to Program 16-Bit, Timer 1 as an event counter:


1. Activate pull-up on T1 (PB0) using C instruction PORTB = 0x01;
2. Load TCCR1A with 0x00 and TCCR1B register with value 0x06 (External clock source on
T1 pin. Clock on falling edge).
3. Now load TCNT1H and TCNT1L with 0x00 to initialize the 16-bit timer with the zero value.
4. Now whenever a falling edge will occur at T1, counter will be incremented.

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 13
Microcontroller Based System Design

//This program generates 5Hz square wave on PA0 with a duty cycle of 50%. ON time
// is 100ms and OFF time is also 100ms.

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

//Macros definition
#define BitGet(p,m) ((p) & (m))
#define BitSet(p,m) ((p) |= (m))
#define BitFlip(p,m) ((p) ^= (m))
#define Bit(x) (0x01 << (x))

void TimerDelay(void); //Function prototype declaration

void main(void)
{
DDRA = 0xFF; //Make PortA output
BitSet(PORTA, Bit(0)); //Initially set PA0

while(1)
{
BitFlip(PORTA, Bit(0)); //Toggle PA0
TimerDelay(); //Generates delay of about 100ms
}
}

/* delay calculation
For a clock generation of 5Hz (200ms), timer should be overflowed twice, so:
Timer overflow @ = 200ms / 2 = 100ms (0.1s high, 0.1s low)
Crystal Clock = 1MHz
Prescaler used = 1024
Timer clock = 1MHz / 1024 = 976.5625 Hz
Timer Period = 1/976.5625 = 1024us
Timer Value = 0.1s / 1024us = 97.65625 = 98 (approx) */

void TimerDelay(void)
{
TCNT0 = 0x9F; // (256+1)-98 = 159 = 0x9F
TCCR0 = 0x05; //Timer0 ON, clk/1024 prescaler, Normal Mode
while(!BitGet(TIFR, Bit(0))); // Wait for timer0 overflow & TOV0 flag is raised
TCCR0 = 0x00; //Stop Timer
BitSet(TIFR, Bit(0)); //Clear TOV0
}

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 14
Microcontroller Based System Design

Simulation:

5Hz square wave generation through timer0

//This program counts the event occur at T1 (PB1) on every falling edge
//using 16-Bit Timer1 as event counter and shows the event count on PORTA and PORTC
//higher and lower byte respectively

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

//Start of main program


void main(void)
{

PORTB = 0x02; //Set a pull-up on PB2 (T1)

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 15
Microcontroller Based System Design

DDRA = 0xFF; //Make PORTA as output


DDRC = 0xFF; //Make PORTA as output

TCCR1A = 0x00; //Enable Counter Mode no falling adge at PB1


TCCR1B = 0x06;
while(1)
{
PORTC = TCNT1H; //Send higher byte of counter to PortC
PORTA = TCNT1L; //Send lower byte of counter to PortA
}
}

Simulation:

16-Bit Counter using Timer1

Home Task:
Generate a Square wave of frequencies according to last two digits of your registration
numbers. Even registration numbers will generate Hertz and odd will generate kHz.

For Example: 1625/BSEE/FET/F11 will generate square wave of 25 kHz.

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 16
Microcontroller Based System Design

Lab No. 4 – Interrupt Programming


Objectives:
 To learn the difference between polling and interrupt based programming
 To use the timer interrupt
 To use external hardware interrupt

Introduction:
There are two methods by which a microcontroller can serve a device

1- Interrupt: In interrupt method, a device sends an interrupt signal to microcontroller.


Upon reception of interrupt, microcontroller stops its working and serves the device.
Program executed after receiving an interrupt is called Interrupt Service Routine (ISR).

2- Polling: In polling, microcontroller continuously monitors the status of device, if the


status is met, microcontroller serves the device. In polling method, microcontroller can
only check single device at a time.

Interrupt Vectors in ATmega16:

Vector
Address Source Interrupt Definition
No.
External Pin, Power-on Reset, Brown-out Reset,
1 $000 Reset
Watchdog Reset, and JTAG AVR Reset
2 $002 INT0 External Interrupt Request 0
3 $004 INT1 External Interrupt Request 1
4 $006 TIMER2 COMP Timer/Counter2 Compare Match
5 $008 TIMER2 OVF Timer/Counter2 Overflow
6 $00A TIMER1 CAPT Timer/Counter1 Capture Event
7 $00C TIMER1 COMPA Timer/Counter1 Compare Match A
8 $00E TIMER1 COMPB Timer/Counter1 Compare Match B
9 $010 TIMER1 OVF TIMER1 OVF Timer/Counter1 Overflow
10 $012 TIMER0 OVF Timer/Counter0 Overflow
11 $014 SPI, STC Serial Transfer Complete
12 $016 USART, RXC Rx Complete
13 $018 USART, UDRE USART Data Register Empty
14 $01A USART, TXC USART, Tx Complete
15 $01C ADC ADC Conversion Complete
16 $01E EE_RDY EEPROM Ready
17 $020 ANA_COMP Analog Comparator
18 $022 TWI Two-wire Serial Interface
19 $024 INT2 External Interrupt Request 2
20 $026 TIMER0 COMP Timer/Counter0 Compare Match
21 $028 SPM_RDY Store Program Memory Ready

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 17
Microcontroller Based System Design

Above table shows the interrupt sources and their interrupt vectors for AVR ATmega16. Memory
locations from 0002 to 0028 locations are reserve for interrupt vectors. Each interrupt has 2
words (4 bytes) of memory space for its ISR. For example, 0012 to 0014 memory space is set
aside for Timer0 overflow ISR.
Usually ISR cannot fit into 4-bytes memory space. So a JMP instruction is kept at the vector
address from where ISR jumps to another location where rest of the code of ISR can be written.
At the end of each ISR, RETI (Return from Interrupt) instruction is placed which gives the
control back to the location from where it was interrupted.

Steps to enable an Interrupt:


To enable any interrupt of AVR, we need to take the following steps:

1 Bit D7 (I) of SREG (Status Register) must be set in order to enable the global interrupt.
Without enabling global interrupt, no interrupt can happen. This can be done by using
SEI (assembly instruction) or sei(); (C instruction).
2 After enabling global interrupt, by setting the IE (Interrupt Enable) bit of each interrupt,
that specific interrupt can be enabled. For example, to enable Timer0 overflow interrupt,
we need to set TOIE0 (Bit0 of TIMSK Register).

When interrupt is executed, Bit D7 of SREG is cleared by the microcontroller to avoid the
occurrence of another interrupt. Moreover, if Timer0 overflow interrupt is enabled, TOV0
(Timer0 Overflow flag) is automatically cleared when microcontroller jumps to the Timer0
overflow interrupt vector table.

TIMER INTERRUPTS:
Timer Interrupt Mask Register (TIMSK) holds the different interrupt enable bits related to timers.

Bit # 7 6 5 4 3 2 1 0
Bit Name OCIE2 T0IE2 TICIE1 OCIE1A OCIE1B TOIE1 OCIE0 TOIE0

TOIE0 Timer0 overflow interrupt enable


OCIE0 Timer0 output compare match interrupt enable
TOIE1 Timer1 overflow interrupt enable
OCIE1B Timer1 output compare B match interrupt enable
OCIE1A Timer1 output compare A match interrupt enable
TICIE1 Timer1 input compare interrupt enable
T0IE2 Timer2 overflow interrupt enable
OCIE2 Timer2 output compare match interrupt enable
These bits, along with D7 of SREG, when set, enable the corresponding interrupt. Upon
execution of interrupt, each flag is cleared by AVR itself and D7 of SREG is also disabled to
avoid further interrupt when ISR of an interrupt is being executed.

TIMSK (Timer Interrupt Mask Register)

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 18
Microcontroller Based System Design

EXTERNAL HARDWARE INTERRUPTS:


There are three external hardware interrupts are INT0, INT1 and INT2 located on pins PD2,
PD3 and PB2 respectively.

Bit # 7 6 5 4 3 2 1 0
Bit Name INT1 INT0 INT2 - - - IVSEL IVCE

INT0 External hardware interrupt request 0 enable


INT1 External hardware interrupt request 1 enable
INT2 External hardware interrupt request 2 enable
GICR (General Interrupt Control Register)

INT0 and INT1 can be programmed to trigger on low level, rising edge, falling edge or both
edges through MCUCR (MCU Control Register). Whereas, INT2 can only be programmed to
trigger on falling or rising edge through MCUCSR (MCU Control and Status Register).

If an interrupt is programmed for edge trigger mode, the pulse must be 1 instruction cycle to
ensure that the transition is seen by microcontroller. If an interrupt is programmed for level
trigger, the pin must be held low for at least 5 machine cycles to cause an interrupt.

Bit # 7 6 5 4 3 2 1 0
Bit Name SE SM2 SM1 SM0 ISC11 ISC10 ISC01 ISC00

ISC01 ISC00 Description


0 0 Low level of INT0 generates an interrupt request
0 1 Any logic change on INT0 generates an interrupt request
1 0 Falling edge of INT0 generates an interrupt request
1 1 Rising edge of INT0 generates an interrupt request

ISC11 ISC10 Description


0 0 Low level of INT1 generates an interrupt request
0 1 Any logic change on INT1 generates an interrupt request
1 0 Falling edge of INT1 generates an interrupt request
1 1 Rising edge of INT1 generates an interrupt request
MCUCR (MCU Control Register)

Bit # 7 6 5 4 3 2 1 0
Bit Name JTD ISC2 - JTRF WDRF BORF EXTRF PORF

ISC2 Description
0 The falling edge of INT2 generates an interrupt request
1 The rising edge of INT2 generates an interrupt request
MCUCSR (MCU Control and Status Register)

GIFR (General Interrupt Flag Register) has external interrupt flags. When an external interrupt is
occurs, corresponding flag of that external interrupt is raised. When microcontroller jumps of the
interrupt vector table, flag is automatically cleared or we can clear the flag by writing high on it.

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 19
Microcontroller Based System Design

Bit # 7 6 5 4 3 2 1 0
Bit Name INTF1 INTF0 INTF2 - - - - -

INTF1 When an external interrupt occurs, its corresponding flag bit in GIFR is set.
INTF0 When AVR jumps to its ISR, this flag is cleared by AVR. For level triggering, pin
INTF2 must be hold for at least 5 instruction cycles to be recognized.

GIFR (General Interrupt Flag Register)

/*
This program generates a square wave of 5Hz (200ms) on PortA, Bit 0 using Timer0 CTC
interrupt. Moreover, at the same time, using External Hardware Interrupt INT2 is
configured on falling edge. Upon each INT2 falling edge interrupt, value of PortD is
incremented.
*/

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

//Macros Definition
#define BitSet(p,m) ((p) |= (m))
#define BitClear(p, m) ((p) &= ~(m))
#define BitFlip(p,m) ((p) ^= (m))
#define Bit(x) (0x01 << (x))

int main(void)
{
DDRD = 0xFF; //Make PortD output
BitSet(DDRA, Bit(0)); //Make PA0 output
BitClear(DDRB, Bit(2)); //Make PB2 as input for INT2
BitSet(PORTB, Bit(2)); //Internally pull-up PB2

BitSet(TIMSK, Bit(1)); //Enable OC0IE bit to enable Timer0 Compare Mode interrupt
BitSet(GICR, Bit(5)); //Enable INT2 bit to enable External Interrupt 2
BitClear(MCUCSR, Bit(6));//Configure Falling edge triggered INT2 interrupt
sei(); //Enable Global Interrupt

OCR0 = 98; //98 calculated in the last lab for 0.1 seconds time
TCCR0 = 0x0D; //0000 1101, CTC Mode, Crystal Clock, 1024 prescaler

while(1); //Stay here forever


}

//Interrupt Service Routines (ISRs) of Timer0 CTC Mode & External Interrupt INT2

ISR (TIMER0_COMP_vect) //ISR for Timer0 CTC Output Compare


{
BitFlip(PORTA, Bit(0)); //Toggle PB0
}

ISR (INT2_vect) //ISR for External Interrupt INT2


{
PORTD++; //At every falling edge of INT2, increment PortD
}

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 20
Microcontroller Based System Design

Simulation:

Home Task:
Repeat the home task of Lab-3. At the same time, interface a push button with external
interrupt0. When this button is pressed (external interrupt 0 is invoked), square wave
generation should be stopped. When this button is pressed again, square wave
generation should start again.

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 21
Microcontroller Based System Design

Lab No. 5 – Serial Port Interfacing and Programming


Objectives:
 To interface the serial port of PC with USART of AVR
 To learn that how to program the USART (Universal Synchronous Asynchronous
Receiver / Transmitter) of AVR to transmit & receive asynchronously

Introduction:
USART of AVR has normal asynchronous, double-speed asynchronous, master synchronous
and slave synchronous mode features. Synchronous modes can be used to transfer data
between AVR and external peripherals such as ADC and EEPROMs etc. In this lab, we will
learn study and program the ATmega16 to transfer the data between AVR and PC using normal
asynchronous mode.

MAX232 – Level Converter IC

The serial port of computer sends/receives data serially at logic levels between -12 to +12V
whereas, microcontroller works at logic levels between 0 to 5V (TTL). So we need a RS-232 to
TTL and TTL to RS-232 converter and this is done by using RS-232 Level Converter IC,
MAX232 between PC and ATmega16.

MAX232 Pin Configuration

DB9 Connecter (Front View)

DB9 Plug (Front View)


ATmega16 connection with MAX232 and DB9 connector

Important Registers and Flags Associated with USART:


Following five registers are associated with the USART of AVR:
UDR: USART Data Register: Holds a byte which is received or to be transmitted via USART

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 22
Microcontroller Based System Design

UCSRA: USART Control Status Register A: For controlling serial communication in AVR
UCSRB: USART Control Status Register B: For controlling serial communication in AVR
UCSRC: USART Control Status Register C: For controlling serial communication in AVR
UBRR: USART Baud Rate Register: Value written in this register determines the baud rate

Baud Rate Calculation:


Relationship between desired baud rate and the Fosc (crystal frequency) is given by:

𝐹𝑜𝑠𝑐
𝐷𝑒𝑠𝑖𝑟𝑒𝑑 𝐵𝑎𝑢𝑑 𝑅𝑎𝑡𝑒 =
16(𝑋 + 1)
or
𝐹𝑜𝑠𝑐
𝑋= −1
16(𝐷𝑒𝑠𝑖𝑟𝑒𝑑 𝐵𝑎𝑢𝑑 𝑅𝑎𝑡𝑒)

Where X is the value loaded in the UBRR for a specific desired baud rate. Above
calculation will be true for default setting upon reset.

UCSRA (USART Control and Status Register A)


Bit # 7 6 5 4 3 2 1 0
Bit Name RXC TXC UDRE FE DOR PE U2X MPCM

RXC USART Receive Complete: When a complete byte is received, this flag is set.
Cleared when buffer is empty. This flag is also used to generate receive complete
interrupt.
TXC USART Transmit Complete: When a complete byte is transmitted, this flag is set.
Cleared when buffer is empty. This flag is also used to generate transmit complete
interrupt. Automatically cleared when interrupt is executed.
UDRE USART Data Register Empty: This flag is set when transmit data buffer is empty
and it is ready to receive new data. If this flag is cleared, data should not be written
into UDR. This flag is also used to generate data register empty interrupt.
FE Framing Error: This bit is set, if there is error in the frame of next received byte.
Frame error is generated when the first stop bit of next character in the received
buffer is zero.
DOR Data Overrun: A data overrun occurs when the received data buffer and received
shift register are full, and a new start bit is detected. Set flag enables data overrun.
PE Parity Error: This bit is set if parity checking is enabled (UPM1 = 1) and the next
character in the receive buffer has a parity error.
U2X Double the USART Transmission Speed: Setting this bit will double the baud
rate for asynchronous communication.
MPCM Multiprocessor Communication Mode: This enables the multi-processor
communication mode. The MPCM is not discussed in this lab

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 23
Microcontroller Based System Design

FE, PE and DOR are valid until UDR is read. Set these to zero for transmission

For crystal frequency of 1MHz and 8MHz, the most commonly used baud rates for
asynchronous operation can be generated by using the UBRR settings shown in the
following table:

Fosc = 1MHz Fosc = 8MHz


Baud Rate
U2X = 0 U2X = 1 U2X = 0 U2X = 1
(bps)
UBRR Error UBRR Error UBRR Error UBRR Error

2400 25 0.2% 51 0.2% 207 0.2% 416 -0.1%

4800 12 0.2% 25 0.2% 103 0.2% 207 0.2%

9600 6 -7.0% 12 0.2% 51 0.2% 103 0.2%

14400 3 8.5% 8 -3.5% 34 -0.8% 68 0.6%

UCSRB (USART Control and Status Register B)


Bit # 7 6 5 4 3 2 1 0
Bit Name RXCIE TXCIE UDRIE RXEN TXEN UCSZ2 RXB8 TXB8

RXCIE USART Receive Complete Interrupt Enable: Setting this bit enables the receive
complete interrupt

TXCIE USART Transmit Complete Interrupt Enable: Setting this bit enables the transmit
complete interrupt

UDRIE USART Data Register Empty Interrupt Enable: Setting this bit enables the data
register empty interrupt

RXEN USART Receive Enable: Setting this bit enables USART receiver

TXEN USART Transmit Enable: Setting this bit enables USART transmitter

UCSZ2 USART Character Size: See bit USCZ0 and USCZ1 in UCSRC

RXB8 Receive data bit 8: When using serial frames with nine data bits, the ninth
received bit of every frame is placed in this RXB8.

TXB8 Transmit data bit 8: When using serial frames with nine data bits, the ninth
transmitted bit of every frame is placed in this TXB8.

UCSRC (USART Control and Status Register C)


Bit # 7 6 5 4 3 2 1 0
Bit Name URSEL UMSEL UPM1 UPM0 USBS UCSZ1 UCSZ0 UCPOL

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 24
Microcontroller Based System Design

URSEL Register Select: Setting this bit enables to change the contents of UCSRC
register else, UBRRH is selected

UMSEL Mode Select: Setting this bit selects Asynchronous mode, else synchronous
mode

UPM1:0 Parity Mode: For parity generation and check


00 Disables
01 Reserved
10 Even Parity
11 Odd Parity

USBS Stop Bit Select: Setting this bit will add 2 stop bits in frame else 1 stop bit

UCSZ1:0 Character Size: Combined with Bit2 (UCSZ2) selects the different data bits in a
frame

UCSZ2 : 0 Character Size


000 5
001 6
010 7
011 8
111 9

UCPOL Clock Parity: Used for synchronous mode only

Steps to Program the AVR to Transmit the Data Serially:


1. Enable the USART transmitter through UCSRB
2. Use 8 data bits, asynchronous mode, 1 stop bit and no parity through UCSRC
3. Calculate the value to be loaded in UBRR for a desired baud rate generation
4. Write the character into UDR which is to be transmitted serially
5. Monitor UDRE of TXC bits to check if character has been transmitted. You can
also enable interrupts associated with above flags to execute their respective
ISRs upon completion of transmission.
6. To transmit next character, go to step 4

Steps to Program the AVR to Receive the Data Serially:


1. Enable the USART receiver through UCSRB
2. Repeat steps 2 and 3 of transmit program
3. Monitor RXC bit to check if character has been received. You can also enable
interrupts associated with above flag to execute its respective ISR upon
reception of one complete character.
4. To transmit next character, go to step 3

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 25
Microcontroller Based System Design

C Code for Serial Communication:


/*
This program receives a character from PC and transmit again to PC it after
incrementing. When transmission is complete, PortA is incremented to show that
transmission interrupt is executed
*/

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

//Macros Definition
#define BitSet(p,m) ((p) |= (m))
#define BitClr(p, m) ((p) &= ~(m))
#define Bit(x) (0x01 << (x))

unsigned char x; //temporary variable, to hold the received character

int main(void)
{
DDRA = 0xFF; //PortA as output

UBRRL = 0x35; //0x35 = 53 ~ 53.0833 = (1000000/(16*1200))-1

BitSet(UCSRB, Bit(7)); //enable Receive Complete Interrupt


BitSet(UCSRB, Bit(6)); //enable Transmit Complete Interrupt
BitSet(UCSRB, Bit(4)); //enable Receiving
BitSet(UCSRB, Bit(3)); //enable Transmission

BitClr(UCSRB, Bit(2)); //enables 8 bit character size


BitSet(UCSRC, Bit(1)); //enables 8 bit character size
BitSet(UCSRC, Bit(2)); //enables 8 bit character size
BitSet(UCSRC, Bit(7)); //writes on UCSRC register if this bit is 1
//when clear, UBRRH value will be updated

sei(); //enable global interrupt


while(1); //stay here forever
}

//ISR for Receive interrupt


ISR (USART_RXC_vect)
{
x = UDR; //Store the received character into x
x++; //increment received character
UDR = x; //Transmit the incremented character
}

//ISR for Transmit interrupt


ISR (USART_TXC_vect) //This interrupt will trigger when transmission is complete
{
PORTA++; //increment PortA to show that transmit interrupt is executed
}

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 26
Microcontroller Based System Design

Simulation:

Home Task:
Through serial port, transmit your name from the serial port to AVR and AVR should
return back first four digits of your registration number. Use crystal oscillator of 1MHz.
Set the baud rate to the nearest available range as per the following formula:

(Goupr No.) x (1800) = Baud Rate

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 27
Microcontroller Based System Design

Lab No. 6 – LCD Interfacing


Objectives:
 To interface the LCD and program AVR to show the characters on 2 x 16 LCD

Introduction:
This lab demonstrated that an LCD can be interfaced in 4-bit mode to an ATmega16 AVR
microcontroller. LCD can also be used in 8-bit mode but the advantage of using it in 4-bit mode is that
we can save the I/O ports of a microcontroller. In 4-bit mode, we need to send the character after
splitting it into higher and lower nibbles (4-bits for data only).

PIN SYMBOL I/O DESCRIPTION


1 Vss - Power supply (GND)
2 Vcc - Power supply (+5V)
3 Vdd - Contrast Settings (0~2V)
0 = Select command reg.
4 RS I
1 = Select data reg. of LCD
0 = Write to LCD
5 R/W I
1 = Read from LCD
6 E I The Enable (E) line allows access to the display through R/W and RS lines
7 DB0 I/O Data bit line 0 (LSB)
8 DB1 I/O Data bit line 1
9 DB2 I/O Data bit line 2
10 DB3 I/O Data bit line 3
11 DB4 I/O Data bit line 4
12 DB5 I/O Data bit line 5 For 4-bit Mode, only these pins are
13 DB6 I/O Data bit line 6 used as data bits
14 DB7 I/O Data bit line 7 (MSB)
15 BLA - Backlight Anode (+)
16 BLK - Backlight Anode (+)
Supply connections and pin diagram of 16x2 LCD

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 28
Microcontroller Based System Design

Following table shows some useful command list which is generally required to interface
and program the microcontroller with LCD.

Line No. Character Positions DDRAM Address

00 01 02 03 – 04 05 06 07 80 81 82 83 – 84 85 86 87
1
08 09 10 11 – 12 13 14 15 88 89 8A 8B – 8C 8D 8E 8F

00 01 02 03 – 04 05 06 07 C0 C1 C2 C3 – C4 C5 C6 C7
2
08 09 10 11 – 12 13 14 15 C8 C9 CA CB – CC CD CE CF

Hitachi 44780 16 x 2 LCD Character Locations

Steps to write on LCD:


To write the data or command on LCD, following steps are undertaken:

1. Set R/W bit to low


2. Set RS bit to logic 0 or 1 (command or character)
3. Set data to data lines (if it is writing)
4. Set E to high and then low for some time
5. Finally write the data from data lines (if it is reading)

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 29
Microcontroller Based System Design

6. C Code to Display a Character Type Array on LCD:

// Program to interface LCD in 4 bit mode with AVR microcontroller


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

//Macros Definition
#define BitSet(p,m) ((p) |= (m))
#define BitClr(p, m) ((p) &= ~(m))
#define BitFlip(p,m) ((p) ^= (m))
#define Bit(x) (0x01 << (x))

void LCD_init();
void cmd_4b(unsigned char);
void data_4b(unsigned char);
void LCDcmd(unsigned char);
void LCDdata(unsigned char);

unsigned int main(void)


{
unsigned char data0[]="DEE";
unsigned char data1[]="FET, IIUI";

unsigned int i=0;


DDRA=0xFF;
LCD_init(); //Initialize LCD

cmd_4b(0x87); //Cursor at Line 1, Position 7


while(data0[i]!='\0') //continue loop until null is arrived
{
data_4b(data0[i]); //send all characters for 4-bit data conversion
_delay_ms(50);
i++; //to access next character of array
}
cmd_4b(0xC4); //Cursor at Line 2, Position 4
i=0;

while(data1[i]!='\0') //continue loop until null is arrived


{
data_4b(data1[i]); //send all characters for 4-bit data conversion
_delay_ms(50);
i++; //to access next character of array
}
while(1);
}

void LCD_init() // Initialize LCD


{
cmd_4b(0x02); //to initialize LCD in 4-bit mode.
cmd_4b(0x28); //to initialize LCD in 2 lines, 5x7 dots and 4bit mode
cmd_4b(0x0C); //Display is ON, cursor OFF
}

void cmd_4b(unsigned char Cmd)


{
char Cmd1;
Cmd1 = Cmd & 0xF0; //mask lower nibble because PA4-PA7 pins are used
LCDcmd(Cmd1); // send to LCD

Cmd = Cmd << 4; //shift left 4 bits

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 30
Microcontroller Based System Design

LCDcmd(Cmd1); // send to LCD


}

void data_4b(unsigned char data_value)


{
char data_value1;
data_value1 = data_value & 0xF0;
LCDdata(data_value1);
data_value1 = data_value << 4;
LCDdata(data_value1);
}

void LCDcmd(unsigned char cmdout)


{
PORTA = cmdout;
BitClr(PORTA, Bit(0)); //Clear RS
BitClr(PORTA, Bit(1)); //Clear RW
BitSet(PORTA, Bit(2)); //Set Enable
_delay_us(200);
BitClr(PORTA, Bit(2)); //Clear Enable
}

void LCDdata(unsigned char dataout)


{
PORTA = dataout;
BitSet(PORTA, Bit(0)); //Set RS
BitClr(PORTA, Bit(1)); //Clear RW
BitSet(PORTA, Bit(2)); //Set Enable
_delay_us(200);
BitClr(PORTA, Bit(2)); //Clear Enable
}

Simulation:

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 31
Microcontroller Based System Design

Lab No. 7 – Analog to Digital Converter (ADC) Programming


Objectives:
 To program and use the ADC feature of ATmega16
 Show the lower byte of ADC digital value on Port D and higher byte on Port B

Introduction:

ADC is used to convert the analog voltages into digital value. ADC is widely used in data
acquisition so most of the modern microcontrollers have on-chip ADC peripheral. ATmega16
has on-chip ADC of 10-bit resolution. It has 8 analog input channels, out of which 7 input
channels can be used for differential input. Two differential input channels (ADC0 and ADC2)
can have the input gain of 10x and 200x.

As the ADC is 10-bit, so the converted digital output is stored in two 8-bit registers ADCL and
ADCH. Reference voltages for ADC can be connected to AVCC (Analog Vcc), internal 2.56V
reference or external AREF pin. Minimum 0V and maximum Vcc can be converted to a digital
value. Successive approximation circuitry converted and analog voltage into digital value. This
circuitry requires a clock frequency between 50 kHz to 100 kHz.

Important Registers Associated with ADC:


Following five registers are associated with the ADC of AVR:
ADCL : Has 8 LSBs of converted digital result
ADCH : Has 2 MSBs of converted digital result
ADMUX : For left / right adjusted result, reference voltage and channel selection
ADCSRA : ADC control and status register
SFIOR : Three MSBs of this register are used to select the auto trigger source of ADC

Single ended result can be found from following formula:

𝑉𝑖𝑛 × 1024
𝐴𝐷𝐶 =
𝑉𝑟𝑒𝑓

where Vin is the voltage on the selected input channel, Vref the selected voltage
reference and ADC is the 10-bit converted digital decimal value.

Similarly, differential input result can be found from following formula:

(𝑉𝑝𝑜𝑠 − 𝑉𝑛𝑒𝑔 ) × 𝐺𝑎𝑖𝑛 × 512


𝐴𝐷𝐶 =
𝑉𝑟𝑒𝑓

where Vpos and Vneg are the two differential input channels and the Gain can be selected
as 1x, 10x and 200x from ADMUX register.

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 32
Microcontroller Based System Design

Bit # 7 6 5 4 3 2 1 0
Bit Name REFS1 REFS0 ADLAR MUX4 MUX3 MUX2 MUX1 MUX0

REFS1:0 Reference selection bits


0 0 AREF, Internal Vref turned off
0 1 AVCC with external capacitor at AREF pin
1 0 Reserved
1 1 Internal 2.56V Voltage Reference with external capacitor at AREF pin

ADLAR ADC Left Adjusted Result. When this bit is set, ADCL contains only two LSBs of
the result at position D7 and D6. Remaining bits are not used

MUX4 : 0 Analog channel and gain selection bits. See following table for details

ADMUX (ADC Multiplexer Selection Register)

Single Ended Positive Negative


MUX4:0 Gain
I/P Differential I/P Differential I/P
00000 ADC0
00001 ADC1
00010 ADC2
00011 ADC3
NA
00100 ADC4
00101 ADC5
00110 ADC6
00111 ADC7
01000* ADC0 ADC0 10x
01001 ADC1 ADC0 10x
01010* ADC0 ADC0 200x
01011 ADC1 ADC0 200x
01100* ADC2 ADC2 10x
01101 ADC3 ADC2 10x
01110* ADC2 ADC2 200x
01111 ADC3 ADC2 200x
10000 ADC0 ADC1 1x
10001* ADC1 ADC1 1x
10010 ADC2 ADC1 1x
NA
10011 ADC3 ADC1 1x
10100 ADC4 ADC1 1x
10101 ADC5 ADC1 1x
10110 ADC6 ADC1 1x
10111 ADC7 ADC1 1x
11000 ADC0 ADC2 1x
11001 ADC1 ADC2 1x
11010* ADC2 ADC2 1x
11011 ADC3 ADC2 1x
11100 ADC4 ADC2 1x
11101 ADC5 ADC1 1x
11110 1.22V(VBG)
NA
11111 0V (GND)
* Not applicable

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 33
Microcontroller Based System Design

Bit # 7 6 5 4 3 2 1 0
Bit Name ADEN ADSC ADATE ADIF ADIE ADPS2 ADPS1 ADPS0

ADEN ADC Enable


ADSC ADC Start conversion. In Single Conversion mode, write this bit to one to start
each conversion.
ADATE ADC Auto Trigger Enable. When this bit is written to one, Auto Triggering of the
ADC is enabled. The ADC will start a con-version on a positive edge of the
selected trigger signal. The trigger source is selected by setting the ADC Trigger
Select bits, ADTS in SFIOR.
ADIF ADC Interrupt Flag. This bit is set when an ADC conversion completes and the
Data Registers are updated. ADIF is cleared by hardware when executing the
corresponding interrupt handling vector otherwise it is cleared by writing a
logical one to the flag
ADIE When this bit is written to one and the I-bit in SREG is set, the ADC Conversion
Complete Inter-rupt is activated.
ADPS2:0 ADC Prescaler Select Bits. These bits determine the division factor between the
XTAL frequency and the input clock to the ADC. See following table

ADCSRA (ADC Control and Status Register A)

ADPS2 ADPS1 ADPS0 Division Factor


0 0 0 Reserved
0 0 1 2
0 1 0 4
0 1 1 8
1 0 0 16
1 0 1 32
1 1 0 64
1 1 1 128

Bit # 7 6 5 4 3 2 1 0
Bit Name ADTS2 ADTS1 ADTS0 - ACME PUD PSR2 PSR10

ADTS2:0 ADC Auto Trigger Source


0 0 0 Free Running Mode
0 0 1 Analog Comparator
0 1 0 External Interrupt Request 0
0 1 1 Timer / Counter 0 compare match
1 0 0 Timer / Counter 0 overflow
1 0 1 Timer / Counter 1 compare match B
1 1 0 Timer / Counter 1 overflow
1 1 1 Timer / Counter 1 capture event
SFIOR (Special Function I/O Register)

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 34
Microcontroller Based System Design

ADC Timing Diagram – Single Conversion

Steps to program A/D converter using interrupts:

1. Make the pin input which is selected as ADC input channel


2. Turn ON the ADC module by setting ADEN of ADCSRA
3. Select the conversion speed using ADPS2:0 bits of ADCSRA
4. Load the appropriate value in ADMUX to select the input channel, reference voltages
and left of right aligned result.
5. Enable the ADC interrupt by setting ADIE bit of ADCSRA and D7 of SREG
6. Now start the conversion by setting ADSC bit of ADCSRA
7. Interrupt will be generated when conversion is done. First read ADCL then ADCH, if
result if right aligned
8. Go to step 6 to read the selected channel again

C Code to Display ADC value on Port A and Port B:

/* This program converts the analog input to 10-bit digital output. ADC0 (channel 0)
is analog input. Lower byte of digital output is shown on Port D and 2 MSB bits out
of 10 bits is shown on Port B */

#include<avr\io.h>
#include<avr\interrupt.h>

/////////////// Macros Definition/////////////////


#define Bit(x) (0x01 << (x))
#define BitSet(p, m) ((p) |= (m))
#define BitClr(p, m) ((p) &= ~(m))

void InitADC(void);

ISR(ADC_vect)
{
PORTD = ADCL;
PORTB = ADCH;

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 35
Microcontroller Based System Design

BitSet(ADCSRA, Bit(6)); //Start conversion again


}

int main(void)
{
DDRA = 0x00; //PortA as input for ADC input
DDRD = 0xFF; //PortD as output for lower byte of Digital value
DDRB = 0xFF; //PortB as output for higher byte of Digital value
InitADC();
sei(); //Enable global interrupt
while(1);
}

void InitADC(void)
{
BitSet(ADMUX, Bit(7)); //Internal 2.56V selected as Vref
BitSet(ADMUX, Bit(6)); //Internal 2.56V selected as Vref
BitClr(ADMUX, Bit(5)); //Right adjusted result
BitClr(ADMUX, Bit(4)); //Single ended (GND as common ground)
BitClr(ADMUX, Bit(3)); //non-differential input on ADC0 channel (PA0, Pin No. 40)
BitClr(ADMUX, Bit(2)); //
BitClr(ADMUX, Bit(1)); //
BitClr(ADMUX, Bit(0)); //
//ADMUX = 0xC0; //Same settings as given above

BitSet(ADCSRA, Bit(7)); //Enable ADC


BitClr(ADCSRA, Bit(5)); //Disable Auto Trigger
BitSet(ADCSRA, Bit(3)); //Enable ADC Interrupt
BitSet(ADCSRA, Bit(2)); //Prescaler = Fosc/128
BitSet(ADCSRA, Bit(1)); //Prescaler = Fosc/128
BitSet(ADCSRA, Bit(0)); //Prescaler = Fosc/128

BitSet(ADCSRA, Bit(6)); //Start Conversion


//ADCSRA = 0xCF ; //Same settings as described above
}

Simulation:

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 36
Microcontroller Based System Design

Lab No. 8 – PWM (Pulse Width Modulation) Programming


Objectives:
 To program and use the PWM feature of ATmega16
 To generate a square wave of 20% duty cycle using PWM feature of AVR

Introduction:

PWM has a wide variety of applications, ranging from measurement and communications to
power control and conversion. One of the popular applications of PWM is the speed control of
DC motors. By varying the duty cycle through PWM, speed of DC motor can be controlled for a
fixed load. Higher the duty cycle, greater the speed of DC motor. AVR feature of PWM enables
us to generate the square wave of desired frequency and pulse width (duty cycle). At the same
time, we can perform the other task as the CPU is not busy in the wave generation.

PWM Modes:

ATmega16 has three timers which can be used as wave generation on their dedicated pins.
There are two basic PWM modes, Fast PWM and Phase Correct PWM.

1- Fast PWM Mode:

In Fast PWM, the TCNT0 counts like it does in Normal Mode. After the timer is started, it starts
to count up. Whenever it rolls over from its Top (0xFF in Timer0) to 0x00, TOV0 flag is raised. It
can be selected by using COM01:00 bits of TCCR0 whether to set or clear the OC0 pin after the
TOV0 flag is raised. While counting from Bottom to Top, compare match occurs when TCNT0
matches OCR0 and on the compare match, OC0 pin can be programmed to set or clear.

For non-inverted Fast PWM mode, upon compare match, OC0 pin clears and upon Top (0xFF)
of TCNT0, OC0 pin sets. For inverted Fast PWM mode, upon compare match, OC0 pins sets
and upon Top (0xFF) of TCNT0, OC0 pin clears. Both of these modes of Fast PWM can be
understood from the Fig 8.1.

Value to be loaded in OCR0 to generate the PWM of required duty cycle can be determined
from the following formula:

𝑂𝐶𝑅0 + 1
𝐷𝑢𝑡𝑦 𝐶𝑦𝑐𝑙𝑒 = × 100 Non-inverted Mode Fast PWM
256

255 − 𝑂𝐶𝑅0
𝐷𝑢𝑡𝑦 𝐶𝑦𝑐𝑙𝑒 = × 100 Inverted Mode Fast PWM
256

WGM01:00 bits of TCCR0 register are used to select the different modes of timer.

Bit # 7 6 5 4 3 2 1 0
Bit Name FOC0 WGM00 COM01 COM00 WGM01 CS02 CS01 CS00
Read/Write W RW RW RW RW RW RW RW
Initial Value 0 0 0 0 0 0 0 0

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 37
Microcontroller Based System Design

FOC0 Force Output Compare: FOC0 bit is only active when the WGM00:1
bits specifies a non-PWM mode.
WGM00 WGM01 Timer Mode 0 Selector Bits (Four modes available)
0 0 Normal Mode
0 1 CTC (Clear Timer on Compare Match) Mode
1 0 PWM, Phase Correct Mode
1 1 Fast PWM

COM01 : COM00 Compare Output Mode: used to select the following operation if Fast
PWM is selected through WGM01:00:
0 0 Disconnect, Normal port operation, OC0 disconnected
0 1 Reserved
1 0 Non-inverted, Clear OC0 on compare match, set OC0 at Top
1 1 Inverted, Set OC0 on compare match, clearOC0 on Top

CS02:00 D2 D1 D0 Timer 0 Clock Source Selector


0 0 0 No clock source (Timer/Counter stopped)
0 0 1 clk (No Prescaling)
0 1 0 clk / 8
0 1 1 clk / 64
1 0 0 clk / 256
1 0 1 clk / 1024
1 1 0 External clock on T0 (PB0) pin. Clock on falling edge
1 1 1 External clock on T0 (PB0) pin. Clock on rising edge

TCCR0 (Timer / Counter Control Register)

Fig 8.1: Fast PWM

2- Phase Correct PWM Mode:

In Phase Correct PWM Mode, the TCNT0 goes up and down like a yo-yo. After the timer is
started, it starts to count up and after reaching Top, it counts downward. Whenever it reaches to
0x00, TOV0 flag is raised. TCNT0 meets the OCR0 two times, one while counting upward and
second while counting downward. It can be selected by using COM01:00 bits of TCCR0

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 38
Microcontroller Based System Design

whether to set or clear the OC0 pin after compare match is occurred while counting upward.
Similarly, while counting downward, on the compare match, OC0 pin can be programmed to set
or clear. In non-inverted phase correct mode, OC0 pin is cleared when compare match occurs
while TCNT0 is counting upward and set OC0 pin when compare match occurs while TCNT0 is
counting downward. Reverse is the case from Inverted phase correct PWM. Both of these
modes of Phase Correct PWM can be understood from the Fig 8.2.

Fig 8.2: Phase Correct PWM

Value to be loaded in OCR0 to generate the PWM of required duty cycle can be determined
from the following formula:

𝑂𝐶𝑅0
𝐷𝑢𝑡𝑦 𝐶𝑦𝑐𝑙𝑒 = × 100 Non-inverted Mode Phase Correct PWM
255

255 − 𝑂𝐶𝑅0
𝐷𝑢𝑡𝑦 𝐶𝑦𝑐𝑙𝑒 = × 100 Inverted Mode Phase Correct PWM
255

In TCCR0, Phase Correct PWM Mode can be selected by WGM01:00 = 01. For Phase Correct
PWM Mode, COM01:00 bits of TCCR0 performs the following operation:

COM01:00 Mode Operation


0 0 Normal Normal port operation, OC0 disconnected

0 1 Reserved

1 1 Non-inverting Clear OC0 on up-counting compare, Set OC0 on down-counting compare

1 1 Inverting Set OC0 on up-counting compare, Clear OC0 on down-counting compare

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 39
Microcontroller Based System Design

As Timer2 is also 8-bit timer, therefore it works similar to Timer0. The differences are the
register names, output pin and the prescaler of TCCRx register. For Timer0 and Timer2 the Top
is fixed (0xFF).

Timer1 is a 16-bit timer. Modes of Timer1 can be selected from TCCR1B TCCR1A registers.
Details of PWM generation through Timer1 are beyond the scope of this lab. However, the basic
principle is same as discussed earlier.

Bit # 7 6 5 4 3 2 1 0
Bit Name ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10
Read/Write RW RW RW RW RW RW RW RW
Initial Value 0 0 0 0 0 0 0 0

ICNC1 D7 Setting this bit enables the input noise canceller

ICES1 D6 Setting this bit enables the input capture on falling edge

WGM00 WGM01 Timer1 Modes (WGM11:10 are in TCCR1A)


WGM Update of TOV Flag
Mode Timer/Counter Mode of Operation Top Top Type
13 12 11 10 OCR1x Set on

1 0 0 0 0 Normal 0xFFFF Fixed Immediate Max


2 0 0 0 1 PWM, Phase Correct, 8 bit 0x00FF Fixed Top Bottom
3 0 0 1 0 PWM, Phase Correct, 9 bit 0x01FF Fixed Top Bottom
4 0 0 1 1 PWM, Phase Correct, 10 bit 0x03FF Fixed Top Bottom
5 0 1 0 0 CTC OCR1A Variable Immediate Max
6 0 1 0 1 Fast PWM, 8 bit 0x00FF Fixed Top Top
7 0 1 1 0 Fast PWM, 9 bit 0x01FF Fixed Top Top
8 0 1 1 1 Fast PWM, 10 bit 0x03FF Fixed Top Top Top
9 1 0 0 0 PWM, Phase & Frequency Correct ICR1 Variable Bottom Bottom
10 1 0 0 1 PWM, Phase & Frequency Correct OCR1A Variable Bottom Bottom
11 1 0 1 0 PWM, Phase Correct ICR1 Variable Top Bottom
12 1 0 1 1 PWM, Phase Correct OCR1A Variable Top Bottom
13 1 1 0 0 CTC ICR1 Variable Immediate Max
14 1 1 0 1 Reserved - - - -
15 1 1 1 0 Fast PWM ICR1 Variable Top Top
16 1 1 1 1 Fast PWM OCR1A Variable Top Top

CS12:10 D2 D1 D0 Timer 1 Clock Source Selector


0 0 0 No clock source (Timer/Counter stopped)
0 0 1 clk (No Prescaling)
0 1 0 clk / 8
0 1 1 clk / 64
1 0 0 clk / 256
1 0 1 clk / 1024
1 1 0 External clock on T1 (PB1) pin. Clock on falling edge
1 1 1 External clock on T1 (PB1) pin. Clock on rising edge
TCCR1B (Timer1 Control Register B)

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 40
Microcontroller Based System Design

C Code for PWM generation using Fast PWM Mode:


/*
This program generates the square wave of 20% duty cycle on OC0 pin of ATmega16 using
the PWM feature of AVR. We would use Fast PWM mode of complete this task

For fast PWM non-inverted mode, formula is as follows:


Duty Cycle = (OCR0 + 1)/256*100
20*256/100 = OCR0 + 1
51 = OCR0 + 1
OCR0 = 50 = 0x32

So, we will load 0x32 in ORC0 in order to generate square wave, having 20% duty cycle
*/

#include<AVR\io.h>
void main(void)
{
DDRB = 0xFF; //Make PortB as output to generate PWM on OC0 (PB3)
OCR0 = 0x32; //to generate 20% duty cycle
TCCR0 = 0x69; //Configure fast PWM, non-inverted, without prescaler
while(1);
}

Simulation:

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 41
Microcontroller Based System Design

Lab No. 9 – SPI (Serial Peripheral Interface) Programming


Objectives:
 To program and use the SPI feature of AVR
 To transmit a character between two ATmega16 microcontrollers

Introduction:
The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the
AVR and peripheral devices or between several AVR devices. The ATmega16 SPI includes the
following features:

 Full-duplex 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
 Double Speed (CK/2) Master SPI Mode

Following figure shows the interconnection between two SPI devices. The system consists of
communication by pulling low the SS pin of desired slave device. SCK is the clock signal which
is generated by Master device. Data between both the devices is exchanged by SCK clock rate.
Data is always shifted from Master to Slave on MOSI (Master Out, Slave In) and from Slave to
Master on MISO (Master In, Slave Out) pin. Master will pull the SS pin high after transmission of
data.

When device is configured as Master, SPI has no control on SS pin. This pin must be controlled
by software. Before start of transmission from Mater to Slave, SS pin must be kept low. 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, the 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

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 42
Microcontroller Based System Design

Register, 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) 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.

For Slave, minimum low and high period of the clock on SCK pin should be longer than 02 CPU
clock cycles.

Following three registers are related to SPI of ATmega16:

 SPSR (SPI Status Register)


 SPCR (SPI Control Register)
 SPDR (SPI Data Register)

Bit # 7 6 5 4 3 2 1 0
Bit Name SPIF WCOL - - - - - SPI2X

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).
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.
SPI2X Double SPI Speed: When this bit is written logic one the SPI speed (SCK
Frequency) will be doubled when the SPI is in Master mode

SPSR (SPI Status Register)

Bit # 7 6 5 4 3 2 1 0
Bit Name SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0

SPIE SPI Interrupt Enable: This bit causes the SPI interrupt to be executed if SPIF
bit in the SPSR Register is set and if the global interrupt enable bit in SREG is
set.
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.
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.
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.

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 43
Microcontroller Based System Design

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
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.
SPR1:0 0 0 Fosc / 4
0 1 Fosc / 16
1 0 Fosc / 64
1 1 Fosc / 128

SPCR (SPI Control Register)

There are four combinations of SCK phase and polarity with respect to serial data, which are
determined by control bits CPOL and CPHA in SPCR register:

SPI Mode CPOL CPHA Operation


0 0 0 Read on rising edge, Setup on falling edge
1 0 1 Read on falling edge, Setup on rising edge
2 1 0 Read on falling edge, Setup on rising edge
3 1 1 Read on rising edge, Setup on falling edge

SPI Transfer Format with CPHA = 0

SPI Transfer Format with CPHA = 1

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 44
Microcontroller Based System Design

C Code for data transfer between two ATmega16 using SPI feature of AVR:
/*
This program transmits a character from first ATmega16 microcontroller and receives
the same on other microcontroller. SPI feature of ATmega16 is used to complete the
task.
*/

///////////////// CODE FOR MASTER/////////////////


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

#define MOSI 5
#define MISO 6
#define SCK 7
#define SS 4

/////////////// Macros Definition/////////////////


#define Bit(x) (0x01 << (x))
#define BitGet1 (p, m) ((p) & (m))
#define BitSet(p, m) ((p) |= (m))
#define BitClr(p, m) ((p) &= ~(m))

void main(void)
{
unsigned char x=0;

DDRB=(1<<SS)|(1<<SCK)|(1<<MOSI); //Make these pins as output


DDRB=~(1<<MISO); //Make MISO as input
BitSet(SPCR, Bit(6)); //Enable SPI
BitSet(SPCR, Bit(4)); //Enable Mater
BitSet(SPCR, Bit(0)); //Select SCK Freq as Fos/16

while(1)
{
BitClr(PORTB, Bit(SS)); //Enable Slave Select Pin
SPDR=x; //Load SPI Data Register for transmission
while(!(BitGet(SPSR, Bit(7)))); //wait until SPI Interrupt Flag is raised
BitSet(PORTB, Bit(SS)); //Disable Slave Select Pin
_delay_ms(500);
x++;
}
}

///////////////// CODE FOR SLAVE/////////////////

#include<avr/io.h>
#define MOSI 5
#define MISO 6
#define SCK 7
#define SS 4

/////////////// Macros Definition/////////////////


#define Bit(x) (0x01 << (x))
#define BitGet(p, m) ((p) & (m))
#define BitSet(p, m) ((p) |= (m))
#define BitClr(p, m) ((p) &= ~(m))

void main(void)
{

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 45
Microcontroller Based System Design

DDRA=0xFF; //Make PortA as output


DDRB=(1<<MISO); //Make MISO as output
BitSet(SPCR, Bit(6)); //Enable SPI
BitClr(SPCR, Bit(4)); //Enable Slave
BitSet(SPCR, Bit(0)); //Select SCK Freq as Fosc/16
while(1)
{
while(!(BitGet(SPSR, Bit(7)))); //wait until SPI Interrupt Flag is raised
PORTA=SPDR;
}
}

Simulation:

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 46
Microcontroller Based System Design

Lab No. 10 – I2C or TWI (Two Wire Interface) Programming


Objectives:
 To program and use the TWI feature of AVR
 To transmit a character from Master and receive at Slave ATmega16 microcontrollers
using TWI feature of AVR

Introduction:
The Two Wire Interface (TWI) protocol allows the systems designer to interconnect up to 128
different devices using only two bi-directional bus lines, one for clock (SCL) and one for data
(SDA). An external pull-up resistor is required to be connected for both the TWI pins to keep the
line in high state when these are not driven by any TWI device. All devices connected to the bus
have individual addresses. In TWI protocol, there are built-in mechanisms to resolve the issues
of bus contention. The ATmega16 TWI includes the following features:

 Simple, powerful and flexible communication interface with only two bus lines
 Master and Slave operation supported
 Device can operate as transmitter and receiver
 7-bit address space allows 128 different slave addresses
 Multi-master arbitration support
 Up to 400 kHz data transfer speed
 Fully programmable slave address with general call support
 Address recognition causes Wake-up when AVR is in Sleep Mode

Following figure show the interconnection of different devices connected to Serial Data (SDA)
and Serial Clock (SCL) pins. If none of device is driving the lines, pull-up resistors will keep the
lines at Vcc potential.

Following figure shows the condition for a valid data:

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 47
Microcontroller Based System Design

START and STOP conditions:


The Master initiates and terminates a data transmission. The transmission is initiated when the
Master issues a START condition on the bus, and it is terminated when the Master issues a
STOP condition. Between a START and a STOP condition, the bus is considered busy, and no
other Master should try to seize control of the bus.

A special case occurs when a new START condition is issued between a START and STOP
condition. This is referred to as a REPEATED START condition, and is used when the Master
wishes to initiate a new transfer without releasing control of the bus. After a REPEATED
START, the bus is considered busy until the next STOP.

As depicted below, START and STOP conditions are signaled by changing the level of the SDA
line when the SCL line is high.

Address Packet Format:


All address packets transmitted on the TWI bus are nine bits long, consisting of seven address
bits, one READ/WRITE control bit and an acknowledge bit. If the READ/WRITE bit is set, a read
operation is to be performed; otherwise a write operation should be performed. When a Slave
recognizes that it is being addressed, it should acknowledge by pulling SDA low in the ninth
SCL (ACK) cycle. If the addressed Slave is busy, or for some other reason cannot service the
Master’s request, the SDA line should be left high in the ACK clock cycle. The Master can then
transmit a STOP condition, or a REPEATED START condition to initiate a new transmission.

The MSB of the address byte is transmitted first. Slave addresses can freely be allocated by the
designer, but the address 0000 000 is reserved for a general call.

Data Packet Format:


All data packets transmitted on the TWI bus are nine bits long, consisting of one data byte and
an acknowledge bit. During a data transfer, the Master generates the clock and the START and

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 48
Microcontroller Based System Design

STOP conditions, while the receiver is responsible for acknowledging the reception. An
Acknowledge (ACK) is signaled by the receiver pulling the SDA line low during the ninth SCL
cycle. If the receiver leaves the SDA line high, a NACK is signaled. When the receiver has
received the last byte, or for some reason cannot receive any more bytes, it should inform the
transmitter by sending a NACK after the final byte.

Block Diagram of TWI Module:

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 49
Microcontroller Based System Design

TWI Registers:
As shown in the above block diagram, TWI module of AVR has following registers:

 TWDR TWI Data register


 TWAR TWI Slave address register
 TWBR TWI Bit Rate register
 TWSR TWI Status register
 TWCR TWI Control register

In receive mode, TWDR will have received byte and in transmit mode, TWDR will have byte to
be transmitted.

TWAR contains the 7-bit slave address to which TWI will respond when working as slave. LSB
(Bit 0) of TWAR is TWGCE. Setting this bit enables the recognition of general call.

TWBR selects the division factor to control the SCL clock frequency while working in Master
mode. SCL frequency can be calculated from following formula:

𝐶𝑃𝑈 𝐶𝑙𝑜𝑐𝑘 𝐹𝑟𝑒𝑞


𝑆𝐶𝐿 𝑓𝑟𝑒𝑞𝑢𝑒𝑛𝑐𝑦 =
16 + 2(𝑇𝑊𝐵𝑅) × 4𝑇𝑊𝑃𝑆

Where, TWBR holds the 8-bit value for a required SCL frequency. TWPS are two bits for
prescaler in TWSR register.

Bit # 7 6 5 4 3 2 1 0
Bit Name TWS7 TWS6 TWS5 TWS4 TWS3 - TWPS1 TWPS0

TWS7:3 TWS: TWI Status: These five bits show the status of TWI control and bus. For
more details, see datasheet

TWPS1:0 TWI Prescaler Bits:


00 1
01 4
10 16
11 64
TWSR (TWI Status Register)

Bit # 7 6 5 4 3 2 1 0
Bit Name TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE

TWINT This bit is set by hardware when the TWI has finished its current job and expects
application software response. If the I-bit in SREG and TWIE in TWCR are set, the
MCU will jump to the TWI Interrupt Vector. While the TWINT Flag is set, the SCL low
period is stretched. The TWINT Flag must be cleared by software by writing a logic
one to it. Note that this flag is not automatically cleared by hardware when executing
the interrupt routine. Also note that clearing this flag starts the operation of the TWI, so
all accesses to the TWI Address Register (TWAR), TWI Status Register (TWSR), and
TWI Data Register (TWDR) must be complete before clearing this flag.

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 50
Microcontroller Based System Design

TWEA The TWEA bit controls the generation of the acknowledge pulse. If the TWEA bit is
written to one, the ACK pulse is generated on the TWI bus if the following conditions
are met:
1. The device’s own Slave address has been received.
2. A general call has been received, while the TWGCE bit in the TWAR is set.
3. A data byte has been received in Master Receiver or Slave Receiver mode.
By writing the TWEA bit to zero, the device can be virtually disconnected from the
Two-wire Serial Bus temporarily. Address recognition can then be resumed by writing
the TWEA bit to one again.

TWSTA The application writes the TWSTA bit to one when it desires to become a Master on
the Two-wire Serial Bus. The TWI hardware checks if the bus is available, and
generates a START condition on the bus if it is free. However, if the bus is not free,
the TWI waits until a STOP condition is detected, and then generates a new START
condition to claim the bus Master status. TWSTA must be cleared by software when
the START condition has been transmitted.

TWSTO Writing the TWSTO bit to one in Master mode will generate a STOP condition on the
Two-wire Serial Bus. When the STOP condition is executed on the bus, the TWSTO
bit is cleared automatically. In Slave mode, setting the TWSTO bit can be used to
recover from an error condition. This will not generate a STOP condition, but the TWI
returns to a well-defined unaddressed Slave mode and releases the SCL and SDA
lines to a high impedance state.

TWWC The Write collusion bit is set when attempting to write to the TWI Data Register TWDR
when TWINT is low. This flag is cleared by writing the TWDR Register when TWINT is
high.

TWEN The TWEN bit enables TWI operation and activates the TWI interface. When TWEN is
written to one, the TWI takes control over the I/O pins connected to the SCL and SDA
pins, enabling the slew-rate limiters and spike filters. If this bit is written to zero, the
TWI is switched off and all TWI transmissions are terminated, regardless of any
ongoing operation.

TWIE When this bit is written to one, and the I-bit in SREG is set, the TWI interrupt request
will be activated for as long as the TWINT Flag is high.

TWCR (TWI Control Register)

C Code for data transfer between two ATmega16 using TWI feature of AVR:
/*
This program transmits a character from Master ATmega16 microcontroller and receives
the same on Slave microcontroller. TWI feature of ATmega16 is used to complete the
task.
*/

///////////////// CODE FOR MASTER/////////////////


#include<avr/io.h>

/////////////// Macros Definition/////////////////


#define Bit(x) (0x01 << (x))
#define BitGet(p, m) ((p) & (m))
#define BitSet(p, m) ((p) |= (m))
#define BitClr(p, m) ((p) &= ~(m))

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 51
Microcontroller Based System Design

void i2c_init(void)
{
TWSR = 0x00; //Use zero prescaler
TWBR = 123; //for SCL Freq = 1kHz and Fosc = 1MHz
TWCR = 0x04; //Enable TWEN, TWI Module
}

void i2c_start(void)
{
BitSet(TWCR, Bit(7)); //Clear TWINT, TWI Interrupt Flag
BitSet(TWCR, Bit(5)); //Enable TWSTA, TWI Start Condition
BitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enable
while(!(BitGet(TWCR, Bit(7)))); //Stay till start condition transmitted
}

void i2c_write(unsigned char x)


{
TWDR = x; //Place date to be transmitted in TWI Data reg
BitSet(TWCR, Bit(7)); //Clear TWEN, TWI Interrupt Flag
BitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enable
while(!(BitGet(TWCR, Bit(7)))); //Stay till data transmitted
}

void i2c_stop(void)
{
BitSet(TWCR, Bit(7)); //Clear TWINT, TWI Interrupt Flag
BitSet(TWCR, Bit(4)); //Enable TWSTA, TWI Stop Condition
BitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enable
while(!(BitGet(TWCR, Bit(7)))); //Stay till stop condition transmitted
}

void main(void)
{
i2c_init(); //initialize TWI module
i2c_start(); //transmit start condition
i2c_write(0b01010101); //call the address of slave 0x55
i2c_write('A'); //Transmit ASCII of character A
i2c_stop(); //Transmit start condition
while(1);
}

///////////////// CODE FOR SLAVE/////////////////


#include<avr/io.h>

/////////////// Macros Definition/////////////////


#define Bit(x) (0x01 << (x))
#define BitGet(p, m) ((p) & (m))
#define BitSet(p, m) ((p) |= (m))
#define BitClr(p, m) ((p) &= ~(m))

void i2c_InitSlave(void)
{
TWCR = 0x04; //Enable TWEN, TWI Module
TWAR = 0b01010101; //Set Slave address
BitSet(TWCR, Bit(7)); //Clear TWINT, TWI Interrupt Flag
BitSet(TWCR, Bit(6)); //Enable TWEA, Send Acknowledge
BitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enable
}

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 52
Microcontroller Based System Design

void i2c_listen(void)
{
while(!(BitGet(TWCR, Bit(7)))); //Stay till data transmitted
}

unsigned char i2c_receive(unsigned char ChkLast)


{
if(!ChkLast) //Place date to be transmitted in TWI Data reg
{
BitSet(TWCR, Bit(7)); //Clear TWINT, TWI Interrupt Flag
BitSet(TWCR, Bit(6)); //Enable TWEA, Send Acknowledge
BitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enable
}
else
{
BitSet(TWCR, Bit(7)); //Clear TWINT, TWI Interrupt Flag
BitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enable
}
while(!(BitGet(TWCR, Bit(7)))); //Stay till data byte received
return (TWDR);
}

void main(void)
{
DDRA = 0xFF;
i2c_InitSlave(); //initialize TWI module
i2c_listen(); //transmit start condition
PORTA = i2c_receive(1); //Receive only one byte
while(1);
}

Simulation:

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 53
Microcontroller Based System Design

Lab No. 11 – Servo Motor Interfacing


Objectives:
 To control the position of Servo Motor using variable PWM generated through AVR

Introduction:
Servo refers to an error sensing feedback control, which is used to correct the performance of a
system. Servo Motors are DC motors equipped with a servo mechanism for precise control of
angular position. The RC servo motors usually have a rotation limit from 0° to 180°. Some
servos also have rotation limit of 360°. But servos do not rotate continuously. Their rotation is
restricted in between the fixed angles.

A servo motor consists of several main parts, the motor and gearbox, a position sensor
(potentiometer), PWM to voltage converter, error amplifier and motor driver. Following figure
shows the block diagram of a typical servo motor.

PWM to Voltage Converter:

The PWM control input is feed to a PWM to voltage converter. This circuit charges a capacitor
at a constant rate while the pulse is high. When the pulse goes low the charge on the capacitor
is fed to the output via a suitable buffer amplifier. This produces a voltage related to the length
of the applied pulse.

The circuit is tuned to produce a useful voltage over a 1ms to 2ms period. The output voltage is
buffered and so does not decay significantly between control pulses.

Position Sensor (Potentiometer):

The current rotational position of the servo motor output shaft is read by a potentiometer which
produces a voltage that is related to the absolute angle of the output shaft. The potentiometer
then feeds its value into the Error Signal Amplifier which compares the current position with the
required position from the PWM to voltage converter.

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 54
Microcontroller Based System Design

Error Signal Amplifier:

The error signal amplifier is an operational amplifier with negative feedback. It will always try to
minimize the difference between the inverting and non-inverting inputs by driving its output in
the correct direction. The output of the error amplifier is either a negative or positive voltage
representing the difference between its inputs. Large error signal will produce higher output
voltages from error signal amplifier.

The error amplifier output is used to drive the motor. If it is positive the motor will turn in one
direction, otherwise in other direction. This allows the error amplifier to reduce the difference
between its inputs (thus closing the negative feedback loop) and so make the servo go to the
commanded position.

A typical value of the pulse width is somewhere in the range of 1.0 to 2.0ms. For a standard
servo, a pulse width between 1.0ms to 2.0ms makes the servo to turn between 0o to 180o.
However, these values could vary depending on the brand and make of the motor. A servo
motor has three wires; two for supply voltages (Vcc and Ground) and third wire is used to supply
the control PWM pulses.

Following figures show the different angle of rotation for the PWM of different duty cycles. Note
that for 1ms duty cycle PWM, servo does not rotate and the maximum rotation i.e. 180 o is
achieved with the PWM having duty cycle of 10% (2ms).

C Code to control and position of servo motor using variable PWM:


/*
This programs generates the PWM of variable size to control the direction of a
servo motor having 0 to 180 rotation. Min. control pulse is 1ms and max. control
pulse is 2ms */

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 55
Microcontroller Based System Design

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

/*
CALCULATION:
We will use mode 14 (as per datasheet of ATmega16) to generate variable top PWM
with ICR1. We need to calculate the top value for 50Hz PWM Freq

Formula:
Freq PWM = Freq cpu /N(1+Top) so
Top = (Freq CPU / (Freq PWM x N))-1
where N is prescaler

Freq CPU = 1MHz


Prescaler = 16
Freq PWM = 50Hz
Top = (1MHz / (50Hz x 8))-1
Top = 2499

Position of Servo Motor against different pulse widths


5% of 20ms = 1ms = 0 degree (min. rotation)
10% of 20ms = 2ms = 180 degrees (max. rotation)

5% Duty Cycle Calculation for non-inverting mode:


Duty Cycle (%) = ((OCR1x + 1) / Top + 1) * 100
5 / 100 = (OCR1x + 1) / (2499 + 1)
0.05 * 2500 = OCR1x + 1
OCR1x = 124

10% Duty Cycle Calculation for non-inverting mode:


Duty Cycle (%) = ((OCR1x + 1) / Top + 1) * 100
10 / 100 = (OCR1x + 1) / (2499 + 1)
0.1 * 2500 = OCR1x + 1
OCR1x = 249
*/

void main(void)
{
unsigned int x;
//Configure Timer1 registers
TCCR1A |= (1<<COM1A1)|(1<<WGM11); //Non-Inverted PWM
TCCR1B |= (1<<WGM13)|(1<<WGM12)|(1<<CS11); //Prescaler=16 Mode 14(Fast PWM)
ICR1 = 2499; //Freq PWM=50Hz, Time Period = 20ms
DDRD = 0xFF; //PWM generation on PortD5
while(1)
{
x = 124; //1ms = 5% of 20ms pulse
OCR1A = x; //0 degree rotation initially
_delay_ms(1000);

while(x <= 249) // continue till 2ms = 10% of 20ms Pulse


{
OCR1A=x;
_delay_ms(50);
x++;
}
}
}

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 56
Microcontroller Based System Design

Simulation:

References:
M.A. Mazidi at. Al., “The AVR Microcontroller and Embedded Systems: Using Assembly
and C” ISBN-13: 978-0-13-800331-9, 2011

Datasheet ATmega16/16L by Atmel Corporation, Available online:


www.atmel.com/Images/doc2466.pdf

Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 57