Sei sulla pagina 1di 55

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. #
1. 2. 3. 4. 5. 6. 7. 8. 9.

Title
I/O Ports Programming & LED Interfacing Seven Segment Display Interfacing Timer and Counter Programming Interrupt Programming Serial Port Interfacing and Programming LCD Interfacing ADC Programming PWM Programming SPI Programming

Page #
2 5 8 14 19 25 29 34 39 44 51

10. I2C or TWI Programming 11. Servo Motor Interfacing

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:
Overview of software and hardware tools used for programming & operation of ATmega16 Basic circuitry required for operation of ATmega16 To understand that how to make a port input or output First C Program to blink LEDs

We will be using the Atmel Studio 4.19 having built-in GCC compiler to write the C code for ATmega16 AVR Microcontroller. Proteus 7.6 for simulation and Genius G540 Universal Programmer for burning the code to ATmega16.

Theory:
Following three registers are associated to each I/O port of ATmega16: DDRx Data Direction Register to set the port input or output PORTx To write data on I/O pin if port configured as output using DDRx PINx To read data from I/O pins if port is configured as input using DDRx DDxn 0 0 1 1 PORTxn 0 1 0 1 I/O Input Input Output Output Comment Tri-state (Hi-Z) Pxn will source current if externally pulled down Output Low (Sink) Output High (Source)

For writing a high byte on Port A, we need to do the following: DDRA = 0xFF; PORTA = 0xFF; //0xFF = 1111 1111 (make Port A as output) //Send 1 to all pins of Port A

For reading a byte from Port A, we need to do the following: unsigned char x; //define a variable to store the value of PINA DDRA =0x00; //0x00 = 0000 0000 (make PORTA as input) x = PINA; //Read value to Port A and store on variable x I/O Ports - Bit Manipulation using Macros: Ports of the AVR ATmega16 cannot be accessed bitwise. So if we want to perform any function on a single bit, following macros can be used for bit manipulation:
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad

Page 2

Microcontroller Based System Design

Macros definition: #define #define #define #define #define #define BitGet(p, m) BitSet(p, m) BitClear(p, m) BitFlip(p, m) BitWrite(c,p,m) Bit(x) ((p) & (m)) ((p) |= (m)) ((p) &= ~(m)) ((p) ^= (m)) (c ? BitSet(p,m) : BitClear(p,m)) (0x01 << (x))

To set bit number 5 of PORTA: Code: BitSet(PORTA, Bit(5));

// Set bit 5 (6th bit from LSB) of PORTA

To clear bit number 6 of PORTA with a bit mask: Code: BitClear(PORTA, 0x40); // PORTA = x0xx xxxx (x are dont cares)

To flip bit number 0 of PORTA: Code: BitFlip(PORTA, Bit(0));

// Toggle Bit 0 of PORTA

To check bit number 3 of PORTA: Code: if(BitGet(PORTA, Bit(3))) //Check if Bit 3 of PORTA == 1

To set or clear bit 0 of PORTB based on bit number 4 of PORTA: Code:

if (BitGet (PORTA, Bit (4))) // If Bit 4 of PORTA == 1 then set Bit 0 of PORTB BitSet ((PORTB, Bit (0)); // Else clear Bit 0 of PORTB else BitClear (PORTB, Bit (0));

To copy the status of single bit of a register to single bit of another register: Code:

BitWrite (BitGet (PORTA, BIT (4)), PORTB, Bit (0)); //PORTB, Bit0 = PORTA, Bit4

C Code to Toggle LEDs on PORTA with a delay of 1 second:


#include<avr/io.h> #include <util/delay.h> void main(void) { DDRA = 0xFF; PORTA = 0xFF; // Standard header file for input and output functionality // For delay function // Set Port A as output, Data Direction Register // activate pull-up resistors when port is configured as input

while(1) //Forever Loop { _delay_ms (1000); //Delay of 1 Second PORTA = ~PORTA; //Toggle state of port A }

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

Page 3

Microcontroller Based System Design

Simulation:

Home Task:
If Bit 0 of PORTB is high, LEDs connected at PORTA will glow from LSB to MSB. If Bit 0 of PORTB is low, LEDs connected at PORTA will light from LSB to MSB.

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

Page 4

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.3 = g // PORTA.6 = d PORTA.1 = a PORTA.4 = dot PORTA.7 = e PORTA.2 = f PORTA.5 = c

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

Page 5

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 = 0xD7 | // | 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); unsigned char SevenSegment[]= void main(void) { DDRA = 0xFF; DDRB = 0xFF; unsigned char i = 0; while(1) { Display(i); i++; if(i > 99) i = 0; } return 0; } //Function prototype declaration { 0xE7, 0x21, 0xCB, 0x6B, 0x2D, 0x6E, 0xEE, 0x23, 0xEF, 0x6F};

// Port A as output // Port B as output

// Displays two digit value on 7 segments

void Display(unsigned char n) { unsigned char units, tens; { tens = n/10; // units = n%10; // for(x = 0; x<1100; x++) // { PORTB = 0xFE; // PORTA = Seven_Segment[units]; // _delay_us(500);

Separate tens from a two digit number Separate units from a two digit number Generate delay of about 1 second Select one display to show units value Display units

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 6

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 7

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: TCCRn: OCRn: TOVn: OCFn: Timer/Counter Reg: Upon reset, it has zero value and counts up with each timer clock Timer/Counter Control Reg: For setting modes of operation of Timer n Output Compare Reg: When contents of TCNT are equal to OCR, OCF flag is raised and value of TCNTn is reset to zero Timer Overflow Flag: When overflow occurs, this flag is raised 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 8

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 # Bit Name
Read/Write Initial Value

7 FOC0
W 0

6 WGM00
RW 0

5 COM01
RW 0

4 COM00
RW 0

3 WGM01
RW 0

2 CS02
RW 0

1 CS01
RW 0

0 CS00
RW 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 WGM01 0 1 0 1 Timer Mode 0 Selector Bits (Four modes available) Normal Mode CTC (Clear Timer on Compare Match) Mode PWM, Phase Correct Mode Fast PWM Compare Output Mode: These bits control waveform generation, if CTC mode is selected through WGM00-01 bits then: Normal mode operation Toggle OC0 (PB3, Pin 4) on compare match Clear OC0 on compare match Set OC0 on compare match Timer 0 Clock Source Selector No clock source (Timer/Counter stopped) clk (No Prescaling) clk / 8 clk / 64 clk / 256 clk / 1024 External clock on T0 (PB0) pin. Clock on falling edge External clock on T0 (PB0) pin. Clock on rising edge

WGM00 0 0 1 1

COM01 : COM00 0 0 1 1 0 1 0 1

CS02:00 D2 D1 D0 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1

TCCR0 (Timer / Counter Control Register)


Bit # Bit Name
Read/Write Initial Value

7 OCF2
W 0

6 TOV2
RW 0

5 ICF1
RW 0

4 OCF1A
RW 0

3 OCF1B
RW 0

2 TOV1
RW 0

1 OCF0
RW 0

0 TOV0
RW 0

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

Page 9

Microcontroller Based System Design

TOV0 OCF0 TOV1 OCF1B OCF1A ICF1 TOV2 OCF2

D0 D1 D2 D3 D4 D5 D6 D7

Timer 0 overflow flag bit (0 = Timer0 did not overflow) Timer 0 output compare flag (0 = compare match did not occur) Timer 1 overflow flag bit Timer 1 output compare B match flag Timer 1 output compare A match flag Input capture flag Timer 2 overflow flag 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. Page 10

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

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) #define BitSet(p,m) #define BitFlip(p,m) #define Bit(x) ((p) & ((p) |= ((p) ^= (0x01 << (m)) (m)) (m)) (x))

void TimerDelay(void); //Function prototype declaration void main(void) { DDRA = 0xFF; BitSet(PORTA, Bit(0));

//Make PortA output //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; TCCR0 = 0x05; while(!BitGet(TIFR, Bit(0))); TCCR0 = 0x00; BitSet(TIFR, Bit(0)); }

// (256+1)-98 = 159 = 0x9F //Timer0 ON, clk/1024 prescaler, Normal Mode // Wait for timer0 overflow & TOV0 flag is raised //Stop Timer //Clear TOV0

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

Page 11

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 12

Microcontroller Based System Design


DDRA DDRC = 0xFF; = 0xFF; //Make PORTA as output //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 13

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 No.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

Address
$000 $002 $004 $006 $008 $00A $00C $00E $010 $012 $014 $016 $018 $01A $01C $01E $020 $022 $024 $026 $028

Source
Reset INT0 INT1 TIMER2 COMP TIMER2 OVF TIMER1 CAPT TIMER1 COMPA TIMER1 COMPB TIMER1 OVF TIMER0 OVF SPI, STC USART, RXC USART, UDRE USART, TXC ADC EE_RDY ANA_COMP TWI INT2 TIMER0 COMP SPM_RDY

Interrupt Definition
External Pin, Power-on Reset, Brown-out Reset, Watchdog Reset, and JTAG AVR Reset External Interrupt Request 0 External Interrupt Request 1 Timer/Counter2 Compare Match Timer/Counter2 Overflow Timer/Counter1 Capture Event Timer/Counter1 Compare Match A Timer/Counter1 Compare Match B TIMER1 OVF Timer/Counter1 Overflow Timer/Counter0 Overflow Serial Transfer Complete Rx Complete USART Data Register Empty USART, Tx Complete ADC Conversion Complete EEPROM Ready Analog Comparator Two-wire Serial Interface External Interrupt Request 2 Timer/Counter0 Compare Match Store Program Memory Ready

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

Page 14

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). 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 # Bit Name TOIE0 OCIE0 TOIE1 OCIE1B OCIE1A TICIE1 T0IE2 OCIE2 7 OCIE2 6 T0IE2 5 TICIE1 4 OCIE1A 3 OCIE1B 2 TOIE1 1 OCIE0 0 TOIE0

Timer0 overflow interrupt enable Timer0 output compare match interrupt enable Timer1 overflow interrupt enable Timer1 output compare B match interrupt enable Timer1 output compare A match interrupt enable Timer1 input compare interrupt enable Timer2 overflow interrupt enable 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 15

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 # Bit Name INT0 INT1 INT2 7 INT1 6 INT0 5 INT2 4 3 2 1 IVSEL 0 IVCE

External hardware interrupt request 0 enable External hardware interrupt request 1 enable 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 # Bit Name ISC01 0 0 1 1 ISC11 0 0 1 1 7 SE ISC00 0 1 0 1 ISC10 0 1 0 1 6 SM2 Description Low level of INT0 generates an interrupt request Any logic change on INT0 generates an interrupt request Falling edge of INT0 generates an interrupt request Rising edge of INT0 generates an interrupt request Description Low level of INT1 generates an interrupt request Any logic change on INT1 generates an interrupt request Falling edge of INT1 generates an interrupt request Rising edge of INT1 generates an interrupt request 5 SM1 4 SM0 3 ISC11 2 ISC10 1 ISC01 0 ISC00

MCUCR (MCU Control Register)


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

Description The falling edge of INT2 generates an interrupt request 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 16

Microcontroller Based System Design

Bit # Bit Name INTF1 INTF0 INTF2

7 INTF1

6 INTF0

5 INTF2

4 -

3 -

2 -

1 -

0 -

When an external interrupt occurs, its corresponding flag bit in GIFR is set. When AVR jumps to its ISR, this flag is cleared by AVR. For level triggering, pin 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) #define BitClear(p, m) #define BitFlip(p,m) #define Bit(x) ((p) |= (m)) ((p) &= ~(m)) ((p) ^= (m)) (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; TCCR0 = 0x0D; } while(1); //98 calculated in the last lab for 0.1 seconds time //0000 1101, CTC Mode, Crystal Clock, 1024 prescaler //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) { PORTD++; } //ISR for External Interrupt INT2 //At every falling edge of INT2, increment PortD

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

Page 17

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 18

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 Page 19

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

Microcontroller Based System Design UCSRA: UCSRB: UCSRC: UBRR: USART Control Status Register A: For controlling serial communication in AVR USART Control Status Register B: For controlling serial communication in AVR USART Control Status Register C: For controlling serial communication in AVR 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:

or = 16(

16( + 1) ) 1

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 # Bit Name 7 RXC 6 TXC 5 UDRE 4 FE 3 DOR 2 PE 1 U2X 0 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. 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. 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. 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. 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. 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. Double the USART Transmission Speed: Setting this bit will double the baud rate for asynchronous communication. Multiprocessor Communication Mode: This enables the multi-processor communication mode. The MPCM is not discussed in this lab Page 20

TXC

UDRE

FE

DOR PE U2X MPCM

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

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 Baud Rate (bps) 2400 4800 9600 14400 25 12 6 3 U2X = 0 UBRR Error 0.2% 0.2% -7.0% 8.5% U2X = 1 UBRR 51 25 12 8 Error 0.2% 0.2% 0.2% -3.5% U2X = 0 UBRR 207 103 51 34 Error 0.2% 0.2% 0.2% -0.8% Fosc = 8MHz U2X = 1 UBRR 416 207 103 68 Error -0.1% 0.2% 0.2% 0.6%

UCSRB (USART Control and Status Register B)


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

RXCIE

USART Receive Complete Interrupt Enable: Setting this bit enables the receive complete interrupt USART Transmit Complete Interrupt Enable: Setting this bit enables the transmit complete interrupt USART Data Register Empty Interrupt Enable: Setting this bit enables the data register empty interrupt USART Receive Enable: Setting this bit enables USART receiver USART Transmit Enable: Setting this bit enables USART transmitter USART Character Size: See bit USCZ0 and USCZ1 in UCSRC Receive data bit 8: When using serial frames with nine data bits, the ninth received bit of every frame is placed in this RXB8. Transmit data bit 8: When using serial frames with nine data bits, the ninth transmitted bit of every frame is placed in this TXB8.

TXCIE

UDRIE

RXEN TXEN UCSZ2 RXB8

TXB8

UCSRC (USART Control and Status Register C)


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

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

Page 21

Microcontroller Based System Design

URSEL
UMSEL

Register Select: Setting this bit enables to change the contents of UCSRC register else, UBRRH is selected Mode Select: Setting this bit selects Asynchronous mode, else synchronous mode Parity Mode: For parity generation and check 00 Disables 01 Reserved 10 Even Parity 11 Odd Parity Stop Bit Select: Setting this bit will add 2 stop bits in frame else 1 stop bit Character Size: Combined with Bit2 (UCSZ2) selects the different data bits in a frame UCSZ2 : 0 000 001 010 011 111 Character Size 5 6 7 8 9

UPM1:0

USBS UCSZ1:0

UCPOL

Clock Parity: Used for synchronous mode only

Steps to Program the AVR to Transmit the Data Serially:


1. 2. 3. 4. 5. Enable the USART transmitter through UCSRB Use 8 data bits, asynchronous mode, 1 stop bit and no parity through UCSRC Calculate the value to be loaded in UBRR for a desired baud rate generation Write the character into UDR which is to be transmitted serially 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 22

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) #define BitClr(p, m) #define Bit(x) unsigned char x; int main(void) { DDRA = 0xFF; UBRRL = 0x35; BitSet(UCSRB, BitSet(UCSRB, BitSet(UCSRB, BitSet(UCSRB, BitClr(UCSRB, BitSet(UCSRC, BitSet(UCSRC, BitSet(UCSRC, sei(); while(1); Bit(7)); Bit(6)); Bit(4)); Bit(3)); Bit(2)); Bit(1)); Bit(2)); Bit(7)); ((p) |= (m)) ((p) &= ~(m)) (0x01 << (x)) //temporary variable, to hold the received character

//PortA as output //0x35 = 53 ~ 53.0833 = (1000000/(16*1200))-1 //enable //enable //enable //enable Receive Complete Interrupt Transmit Complete Interrupt Receiving Transmission

//enables 8 bit character size //enables 8 bit character size //enables 8 bit character size //writes on UCSRC register if this bit is 1 //when clear, UBRRH value will be updated //enable global interrupt //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 23

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 24

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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

SYMBOL Vss Vcc Vdd RS R/W E DB0 DB1 DB2 DB3 DB4 DB5 DB6 DB7 BLA BLK

I/O I I I I/O I/O I/O I/O I/O I/O I/O I/O -

DESCRIPTION Power supply (GND) Power supply (+5V) Contrast Settings (0~2V) 0 = Select command reg. 1 = Select data reg. of LCD 0 = Write to LCD 1 = Read from LCD The Enable (E) line allows access to the display through R/W and RS lines Data bit line 0 (LSB) Data bit line 1 Data bit line 2 Data bit line 3 Data bit line 4 Data bit line 5 Data bit line 6 Data bit line 7 (MSB) Backlight Anode (+) Backlight Anode (+) Supply connections and pin diagram of 16x2 LCD For 4-bit Mode, only these pins are used as data bits

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

Page 25

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

Character Positions 00 01 02 03 08 09 10 11 00 01 02 03 08 09 10 11 04 05 06 07 12 13 14 15 04 05 06 07 12 13 14 15

DDRAM Address 80 81 82 83 88 89 8A 8B C0 C1 C2 C3 C8 C9 CA CB 84 85 86 87 8C 8D 8E 8F C4 C5 C6 C7 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. 2. 3. 4. 5.

Set R/W bit to low Set RS bit to logic 0 or 1 (command or character) Set data to data lines (if it is writing) Set E to high and then low for some time Finally write the data from data lines (if it is reading)

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

Page 26

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) #define BitClr(p, m) #define BitFlip(p,m) #define Bit(x) void void void void void

((p) |= (m)) ((p) &= ~(m)) ((p) ^= (m)) (0x01 << (x))

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

unsigned int main(void) { unsigned char data0[]="DEE"; unsigned char data1[]="FET, IIUI"; unsigned int i=0; DDRA=0xFF; LCD_init(); cmd_4b(0x87); while(data0[i]!='\0') { data_4b(data0[i]); _delay_ms(50); i++; } cmd_4b(0xC4); i=0; while(data1[i]!='\0') { data_4b(data1[i]); _delay_ms(50); i++; } while(1);

//Initialize LCD //Cursor at Line 1, Position 7 //continue loop until null is arrived //send all characters for 4-bit data conversion //to access next character of array //Cursor at Line 2, Position 4 //continue loop until null is arrived //send all characters for 4-bit data conversion //to access next character of array

void LCD_init() { cmd_4b(0x02); cmd_4b(0x28); cmd_4b(0x0C); }

// Initialize LCD //to initialize LCD in 4-bit mode. //to initialize LCD in 2 lines, 5x7 dots and 4bit mode //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 27

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 28

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 ADCH ADMUX : Has 8 LSBs of converted digital result : Has 2 MSBs of converted digital result : 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 29

Microcontroller Based System Design

Bit # Bit Name REFS1:0

7 REFS1

6 REFS0

5 ADLAR

4 MUX4

3 MUX3

2 MUX2

1 MUX1

0 MUX0

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 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 Analog channel and gain selection bits. See following table for details

ADLAR

MUX4 : 0

ADMUX (ADC Multiplexer Selection Register)


MUX4:0 00000 00001 00010 00011 00100 00101 00110 00111 01000* 01001 01010* 01011 01100* 01101 01110* 01111 10000 10001* 10010 10011 10100 10101 10110 10111 11000 11001 11010* 11011 11100 11101 11110 11111
* Not applicable

Single Ended I/P ADC0 ADC1 ADC2 ADC3 ADC4 ADC5 ADC6 ADC7

Positive Differential I/P

Negative Differential I/P

Gain

NA

NA

ADC0 ADC1 ADC0 ADC1 ADC2 ADC3 ADC2 ADC3 ADC0 ADC1 ADC2 ADC3 ADC4 ADC5 ADC6 ADC7 ADC0 ADC1 ADC2 ADC3 ADC4 ADC5

ADC0 ADC0 ADC0 ADC0 ADC2 ADC2 ADC2 ADC2 ADC1 ADC1 ADC1 ADC1 ADC1 ADC1 ADC1 ADC1 ADC2 ADC2 ADC2 ADC2 ADC2 ADC1 NA

10x 10x 200x 200x 10x 10x 200x 200x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x

1.22V(VBG) 0V (GND)

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

Page 30

Microcontroller Based System Design

Bit # Bit Name ADEN ADSC ADATE

7 ADEN

6 ADSC

5 ADATE

4 ADIF

3 ADIE

2 ADPS2

1 ADPS1

0 ADPS0

ADC Enable ADC Start conversion. In Single Conversion mode, write this bit to one to start each conversion. 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. 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 When this bit is written to one and the I-bit in SREG is set, the ADC Conversion Complete Inter-rupt is activated. ADC Prescaler Select Bits. These bits determine the division factor between the XTAL frequency and the input clock to the ADC. See following table

ADIF

ADIE ADPS2:0

ADCSRA (ADC Control and Status Register A) ADPS2


0 0 0 0 1 1 1 1

ADPS1
0 0 1 1 0 0 1 1

ADPS0
0 1 0 1 0 1 0 1

Division Factor
Reserved 2 4 8 16 32 64 128

Bit # Bit Name ADTS2:0 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1

7 ADTS2

6 ADTS1

5 ADTS0

4 -

3 ACME

2 PUD

1 PSR2

0 PSR10

ADC Auto Trigger Source Free Running Mode Analog Comparator External Interrupt Request 0 Timer / Counter 0 compare match Timer / Counter 0 overflow Timer / Counter 1 compare match B Timer / Counter 1 overflow Timer / Counter 1 capture event

SFIOR (Special Function I/O Register)

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

Page 31

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 32

Microcontroller Based System Design


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

int main(void) { DDRA = 0x00; DDRD = 0xFF; DDRB = 0xFF; InitADC(); sei(); while(1); }

//PortA as input for ADC input //PortD as output for lower byte of Digital value //PortB as output for higher byte of Digital value //Enable global interrupt

void InitADC(void) { BitSet(ADMUX, Bit(7)); BitSet(ADMUX, Bit(6)); BitClr(ADMUX, Bit(5)); BitClr(ADMUX, Bit(4)); BitClr(ADMUX, Bit(3)); BitClr(ADMUX, Bit(2)); BitClr(ADMUX, Bit(1)); BitClr(ADMUX, Bit(0)); //ADMUX = 0xC0; BitSet(ADCSRA, BitClr(ADCSRA, BitSet(ADCSRA, BitSet(ADCSRA, BitSet(ADCSRA, BitSet(ADCSRA, Bit(7)); Bit(5)); Bit(3)); Bit(2)); Bit(1)); Bit(0));

//Internal 2.56V selected as Vref //Internal 2.56V selected as Vref //Right adjusted result //Single ended (GND as common ground) //non-differential input on ADC0 channel (PA0, Pin No. 40) // // // //Same settings as given above //Enable ADC //Disable Auto Trigger //Enable ADC Interrupt //Prescaler = Fosc/128 //Prescaler = Fosc/128 //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 33

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 256 0 100 Non-inverted Mode Fast PWM

WGM01:00 bits of TCCR0 register are used to select the different modes of timer.
Bit # Bit Name
Read/Write Initial Value

255 256
6

Inverted Mode Fast PWM

7 FOC0
W 0

5 COM01
RW 0

4 COM00
RW 0

3 WGM01
RW 0

2 CS02
RW 0

1 CS01
RW 0

0 CS00
RW 0

WGM00
RW 0

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

Page 34

Microcontroller Based System Design

FOC0 WGM00 0 0 1 1 WGM01 0 1 0 1

Force Output Compare: FOC0 bit is only active when the WGM00:1 bits specifies a non-PWM mode. Timer Mode 0 Selector Bits (Four modes available) Normal Mode CTC (Clear Timer on Compare Match) Mode PWM, Phase Correct Mode Fast PWM Compare Output Mode: used to select the following operation if Fast PWM is selected through WGM01:00: Disconnect, Normal port operation, OC0 disconnected Reserved Non-inverted, Clear OC0 on compare match, set OC0 at Top Inverted, Set OC0 on compare match, clearOC0 on Top Timer 0 Clock Source Selector No clock source (Timer/Counter stopped) clk (No Prescaling) clk / 8 clk / 64 clk / 256 clk / 1024 External clock on T0 (PB0) pin. Clock on falling edge External clock on T0 (PB0) pin. Clock on rising edge

COM01 : COM00 0 0 1 1 0 1 0 1

CS02:00 D2 D1 D0 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1

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 35

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 255 Non-inverted Mode Phase Correct PWM

255 255

100

Inverted Mode Phase Correct PWM

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
0 0 1 1 0 1 1 1

Mode
Normal Reserved

Operation
Normal port operation, OC0 disconnected

Non-inverting Clear OC0 on up-counting compare, Set OC0 on down-counting compare 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 36

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 # Bit Name
Read/Write Initial Value

7 ICNC1
RW 0

6 ICES1
RW 0

5 RW 0

4 WGM13
RW 0

3 WGM12
RW 0

2 CS12
RW 0

1 CS11
RW 0

0 CS10
RW 0

ICNC1 ICES1 WGM00


Mode 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 13 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 12 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1

D7 D6 WGM01
WGM 11 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 10 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

Setting this bit enables the input noise canceller Setting this bit enables the input capture on falling edge Timer1 Modes (WGM11:10 are in TCCR1A)
Timer/Counter Mode of Operation Normal PWM, Phase Correct, 8 bit PWM, Phase Correct, 9 bit PWM, Phase Correct, 10 bit CTC Fast PWM, 8 bit Fast PWM, 9 bit Fast PWM, 10 bit PWM, Phase & Frequency Correct PWM, Phase & Frequency Correct PWM, Phase Correct PWM, Phase Correct CTC Reserved Fast PWM Fast PWM Top 0xFFFF 0x00FF 0x01FF 0x03FF OCR1A 0x00FF 0x01FF 0x03FF ICR1 OCR1A ICR1 OCR1A ICR1 ICR1 OCR1A Top Type Fixed Fixed Fixed Fixed Variable Fixed Fixed Fixed Variable Variable Variable Variable Variable Variable Variable Update of OCR1x Immediate Top Top Top Immediate Top Top Top Bottom Bottom Top Top Immediate Top Top TOV Flag Set on Max Bottom Bottom Bottom Max Top Top Top Top Bottom Bottom Bottom Bottom Max Top Top

CS12:10 D2 D1 D0 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1

Timer 1 Clock Source Selector No clock source (Timer/Counter stopped) clk (No Prescaling) clk / 8 clk / 64 clk / 256 clk / 1024 External clock on T1 (PB1) pin. Clock on falling edge 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 37

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 38

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 39

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)
7 SPIF 6 WCOL 5 4 3 2 1 0 SPI2X

Bit # Bit Name 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). 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. 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

WCOL

SPI2X

SPSR (SPI Status Register)


Bit # Bit Name 7 SPIE 6 SPE 5 DORD 4 MSTR 3 CPOL 2 CPHA 1 SPR1 0 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. SPI Enable: When the SPE bit is written to one, the SPI is enabled. This bit must be set to enable any SPI operations. 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. 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.

SPE DORD

MSTR

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

Page 40

Microcontroller Based System Design


CPOL CPHA SPR1:0 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 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. 0 0 1 1 0 1 0 1 Fosc / 4 Fosc / 16 Fosc / 64 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 0 1 2 3 CPOL 0 0 1 1 CPHA 0 1 0 1 Operation Read on rising edge, Setup on falling edge Read on falling edge, Setup on rising edge Read on falling edge, Setup on rising edge 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 41

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 #define #define #define MOSI MISO SCK SS 5 6 7 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); DDRB=~(1<<MISO); BitSet(SPCR, Bit(6)); BitSet(SPCR, Bit(4)); BitSet(SPCR, Bit(0)); while(1) { BitClr(PORTB, Bit(SS)); SPDR=x; while(!(BitGet(SPSR, Bit(7)))); BitSet(PORTB, Bit(SS)); _delay_ms(500); x++; } //Make these pins as output //Make MISO as input //Enable SPI //Enable Mater //Select SCK Freq as Fos/16

//Enable Slave Select Pin //Load SPI Data Register for transmission //wait until SPI Interrupt Flag is raised //Disable Slave Select Pin

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

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 43

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 44

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 Masters 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 45

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 46

Microcontroller Based System Design

TWI Registers:
As shown in the above block diagram, TWI module of AVR has following registers: TWDR TWAR TWBR TWSR TWCR TWI Data register TWI Slave address register TWI Bit Rate register TWI Status register 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: =

Where, TWBR holds the 8-bit value for a required SCL frequency. TWPS are two bits for prescaler in TWSR register.
Bit # Bit Name 7 TWS7 6 TWS6 5 TWS5 4 TWS4 3 TWS3 2 1 TWPS1 0 TWPS0

16 + 2(

)4

TWS7:3

TWS: TWI Status: These five bits show the status of TWI control and bus. For more details, see datasheet TWI Prescaler Bits: 00 1 01 4 10 16 11 64

TWPS1:0

TWSR (TWI Status Register)


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

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 47

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

TWSTA

TWSTO

TWWC

TWEN

TWIE

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 48

Microcontroller Based System Design


void i2c_init(void) { TWSR = 0x00; TWBR = 123; TWCR = 0x04; } void i2c_start(void) { BitSet(TWCR, Bit(7)); BitSet(TWCR, Bit(5)); BitSet(TWCR, Bit(2)); while(!(BitGet(TWCR, Bit(7)))); } void i2c_write(unsigned char x) { TWDR = x; BitSet(TWCR, Bit(7)); BitSet(TWCR, Bit(2)); while(!(BitGet(TWCR, Bit(7)))); } void i2c_stop(void) { BitSet(TWCR, Bit(7)); BitSet(TWCR, Bit(4)); BitSet(TWCR, Bit(2)); while(!(BitGet(TWCR, Bit(7)))); } void main(void) { i2c_init(); i2c_start(); i2c_write(0b01010101); i2c_write('A'); i2c_stop(); while(1); }

//Use zero prescaler //for SCL Freq = 1kHz and Fosc = 1MHz //Enable TWEN, TWI Module

//Clear TWINT, TWI Interrupt Flag //Enable TWSTA, TWI Start Condition //Enable TWEN, TWI Module Enable //Stay till start condition transmitted

//Place date to be transmitted in TWI Data reg //Clear TWEN, TWI Interrupt Flag //Enable TWEN, TWI Module Enable //Stay till data transmitted

//Clear TWINT, TWI Interrupt Flag //Enable TWSTA, TWI Stop Condition //Enable TWEN, TWI Module Enable //Stay till stop condition transmitted

//initialize TWI module //transmit start condition //call the address of slave 0x55 //Transmit ASCII of character A //Transmit start condition

///////////////// 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; TWAR = 0b01010101; BitSet(TWCR, Bit(7)); BitSet(TWCR, Bit(6)); BitSet(TWCR, Bit(2)); }

//Enable TWEN, TWI Module //Set Slave address //Clear TWINT, TWI Interrupt Flag //Enable TWEA, Send Acknowledge //Enable TWEN, TWI Module Enable

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

Page 49

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(); i2c_listen(); PORTA = i2c_receive(1); while(1); }

//initialize TWI module //transmit start condition //Receive only one byte

Simulation:

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

Page 50

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

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

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. 180o 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 52

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 Prescaler = Freq PWM Top = Top = = 1MHz 16 = 50Hz (1MHz / (50Hz x 8))-1 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) { OCR1A=x; _delay_ms(50); x++; } // continue till 2ms = 10% of 20ms Pulse

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

Page 53

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 54

Potrebbero piacerti anche