1-microcontroller based system design - complete
TRANSCRIPT
-
8/13/2019 1-Microcontroller Based System Design - Complete
1/55
Department of Electronic Engineering
Faculty of Engineering & Technology
International Islamic University, Islamabad
Microcontroller Based
System Design
Prepared By: Engr. Muhammad Muzammil
Name:
Reg No.
Section:
Revised on: 27th August, 2013
-
8/13/2019 1-Microcontroller Based System Design - Complete
2/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 1
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
-
8/13/2019 1-Microcontroller Based System Design - Complete
3/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 2
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 havingbuilt-in GCC compiler to write the C code forATmega16 AVR Microcontroller. Proteus 7.6 forsimulation and Genius G540 UniversalProgrammer for burning the code to ATmega16.
Theory:
Following three registers are associated to eachI/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 PORTxn I/O Comment
0 0 Input Tri-state (Hi-Z)
0 1 Input Pxn will source current if externallypulled down
1 0 Output Output Low (Sink)
1 1 Output Output High (Source)
For writing a high byte on Port A, we need to do the following:
DDRA = 0xFF; //0xFF = 1111 1111 (make Port A as output)PORTA = 0xFF; //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 PINADDRA =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 functionon a single bit, following macros can be used for bit manipulation:
-
8/13/2019 1-Microcontroller Based System Design - Complete
4/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 3
Macros definition:
#define BitGet(p, m) ((p) & (m))#define BitSet(p, m) ((p) |= (m))#define BitClear(p, m) ((p) &= ~(m))#define BitFlip(p, m) ((p) = (m))#define BitWrite(c,p,m) (c ? BitSet(p,m) : BitClear(p,m))#define Bit(x) (0x01
-
8/13/2019 1-Microcontroller Based System Design - Complete
5/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 4
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.
-
8/13/2019 1-Microcontroller Based System Design - Complete
6/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 5
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
#include
// PORTA.0 = b PORTA.1 = a PORTA.2 = f
// PORTA.3 = g PORTA.4 = dot PORTA.5 = c
// PORTA.6 = d PORTA.7 = e
-
8/13/2019 1-Microcontroller Based System Design - Complete
7/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 6
// 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); //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;
{
tens = n/10; // Separate tens from a two digit number
units = n%10; // Separate units from a two digit number
for(x = 0; x
-
8/13/2019 1-Microcontroller Based System Design - Complete
8/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 7
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.
-
8/13/2019 1-Microcontroller Based System Design - Complete
9/55
-
8/13/2019 1-Microcontroller Based System Design - Complete
10/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 9
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/WriteInitial Value
W0
RW0
RW0
RW0
RW0
RW0
RW0
RW0
FOC0 Force Output Compare: FOC0 bit is only active when the WGM00:1bits specifies a non-PWM mode. This bit is always read as zero. Whenthis bit is set, and a compare with
WGM00 WGM01 Timer Mode 0 Selector Bits (Four modes available)0 0 Normal Mode0 1 CTC (Clear Timer on Compare Match) Mode1 0 PWM, Phase Correct Mode1 1 Fast PWM
COM01 : COM00 Compare Output Mode: These bits control waveform generation, ifCTC mode is selected through WGM00-01 bits then:
0 0 Normal mode operation0 1 Toggle OC0 (PB3, Pin 4) on compare match1 0 Clear OC0 on compare match1 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 / 80 1 1 clk / 641 0 0 clk / 2561 0 1 clk / 10241 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/WriteInitial Value
W0
RW0
RW0
RW0
RW0
RW0
RW0
RW0
-
8/13/2019 1-Microcontroller Based System Design - Complete
11/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 10
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 flagTOV2 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.
-
8/13/2019 1-Microcontroller Based System Design - Complete
12/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 11
//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#include
//Macros definition
#define BitGet(p,m) ((p) & (m))#define BitSet(p,m) ((p) |= (m))#define BitFlip(p,m) ((p) = (m))#define Bit(x) (0x01
-
8/13/2019 1-Microcontroller Based System Design - Complete
13/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 12
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#include
//Start of main programvoid main(void){
PORTB = 0x02; //Set a pull-up on PB2 (T1)
-
8/13/2019 1-Microcontroller Based System Design - Complete
14/55
-
8/13/2019 1-Microcontroller Based System Design - Complete
15/55
-
8/13/2019 1-Microcontroller Based System Design - Complete
16/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 15
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 enableTICIE1 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. Uponexecution of interrupt, each flag is cleared by AVR itself and D7 of SREG is also disabled toavoid further interrupt when ISR of an interrupt is being executed.
TIMSK (Timer Interrupt Mask Register)
-
8/13/2019 1-Microcontroller Based System Design - Complete
17/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 16
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 toensure 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.
-
8/13/2019 1-Microcontroller Based System Design - Complete
18/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 17
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.When AVR jumps to its ISR, this flag is cleared by AVR. For level triggering, pinmust be hold for at least 5 instruction cycles to be recognized.
INTF0
INTF2
GIFR (General Interrupt Flag Register)
/*
This program generates a square wave of 5Hz (200ms) on PortA, Bit 0 using Timer0 CTCinterrupt. Moreover, at the same time, using External Hardware Interrupt INT2 is
configured on falling edge. Upon each INT2 falling edge interrupt, value of PortD isincremented.*/
#include#include
//Macros Definition
#define BitSet(p,m) ((p) |= (m))#define BitClear(p, m) ((p) &= ~(m))#define BitFlip(p,m) ((p) = (m))#define Bit(x) (0x01
-
8/13/2019 1-Microcontroller Based System Design - Complete
19/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 18
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.
-
8/13/2019 1-Microcontroller Based System Design - Complete
20/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 19
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
ATmega16 connection with MAX232 and DB9 connector
DB9 Connecter (Front View)
DB9 Plug (Front View)
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
-
8/13/2019 1-Microcontroller Based System Design - Complete
21/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 20
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
=16( )
1
Where X is the value loaded in the UBRR for a specific desired baud rate. Abovecalculation 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 completeinterrupt. Automatically cleared when interrupt is executed.
UDRE USART Data Register Empty: This flag is set when transmit data buffer is emptyand it is ready to receive new data. If this flag is cleared, data should not be writteninto 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 receivedbuffer is zero.
DOR Data Overrun:A data overrun occurs when the received data buffer and receivedshift 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 nextcharacter in the receive buffer has a parity error.
U2X Double the USART Transmission Speed: Setting this bit will double the baudrate for asynchronous communication.
MPCM Multiprocessor Communication Mode: This enables the multi-processorcommunication mode. The MPCM is not discussed in this lab
-
8/13/2019 1-Microcontroller Based System Design - Complete
22/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 21
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:
Baud Rate(bps)
Fos c = 1MHz Fos c = 8MHz
U2X = 0 U2X = 1 U2X = 0 U2X = 1
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 receivecomplete interrupt
TXCIE USART Transmit Complete Interrupt Enable: Setting this bit enables the transmitcomplete interrupt
UDRIE USART Data Register Empty Interrupt Enable: Setting this bit enables the dataregister 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 ninthreceived 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
-
8/13/2019 1-Microcontroller Based System Design - Complete
23/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 22
URSEL Register Select: Setting this bit enables to change the contents of UCSRCregister else, UBRRH is selected
UMSEL Mode Select: Setting this bit selects Asynchronous mode, else synchronousmode
UPM1:0 Parity Mode: For parity generation and check00 Disables01 Reserved10 Even Parity11 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 aframe
UCSZ2 : 0 Character Size
0 0 0 50 0 1 60 1 0 70 1 1 81 1 1 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 UCSRC3. 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
-
8/13/2019 1-Microcontroller Based System Design - Complete
24/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 23
C Code for Serial Communication:
/*This program receives a character from PC and transmit again to PC it afterincrementing. When transmission is complete, PortA is incremented to show thattransmission interrupt is executed*/
#include#include
//Macros Definition#define BitSet(p,m) ((p) |= (m))#define BitClr(p, m) ((p) &= ~(m))#define Bit(x) (0x01
-
8/13/2019 1-Microcontroller Based System Design - Complete
25/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 24
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
-
8/13/2019 1-Microcontroller Based System Design - Complete
26/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 25
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)
4 RS I0 = Select command reg.
1 = Select data reg. of LCD
5 R/W I0 = Write to LCD
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
For 4-bit Mode, only these pins areused as data bits
12 DB5 I/O Data bit line 5
13 DB6 I/O Data bit line 6
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
-
8/13/2019 1-Microcontroller Based System Design - Complete
27/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 26
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
100 01 02 03 04 05 06 0708 09 10 11 12 13 14 15
80 81 82 83 84 85 86 8788 89 8A 8B 8C 8D 8E 8F
200 01 02 03 04 05 06 0708 09 10 11 12 13 14 15
C0 C1 C2 C3 C4 C5 C6 C7C8 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)
-
8/13/2019 1-Microcontroller Based System Design - Complete
28/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 27
6. C Code to Display a Character Type Array on LCD:
// Program to interface LCD in 4 bit mode with AVR microcontroller
#include#include
//Macros Definition#define BitSet(p,m) ((p) |= (m))#define BitClr(p, m) ((p) &= ~(m))#define BitFlip(p,m) ((p) = (m))#define Bit(x) (0x01
-
8/13/2019 1-Microcontroller Based System Design - Complete
29/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 28
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
-
8/13/2019 1-Microcontroller Based System Design - Complete
30/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 29
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 digitalvalue. 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 Vnegare the two differential input channels and the Gain can be selected
as 1x, 10x and 200x from ADMUX register.
-
8/13/2019 1-Microcontroller Based System Design - Complete
31/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 30
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 pin1 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 ofthe 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)
MUX4:0Single Ended
I/PPositive
Differential I/PNegative
Differential I/PGain
00000 ADC0
NA
00001 ADC1
00010 ADC2
00011 ADC3
00100 ADC4
00101 ADC5
00110 ADC6
00111 ADC7
01000*
NA
ADC0 ADC0 10x
01001 ADC1 ADC0 10x
01010* ADC0 ADC0 200x
01011 ADC1 ADC0 200x
01100* ADC2 ADC2 10x01101 ADC3 ADC2 10x
01110* ADC2 ADC2 200x
01111 ADC3 ADC2 200x
10000 ADC0 ADC1 1x
10001* ADC1 ADC1 1x
10010 ADC2 ADC1 1x
10011 ADC3 ADC1 1x
10100 ADC4 ADC1 1x
10101 ADC5 ADC1 1x
10110 ADC6 ADC1 1x
10111 ADC7 ADC1 1x
11000 ADC0 ADC2 1x11001 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
-
8/13/2019 1-Microcontroller Based System Design - Complete
32/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 31
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 theselected trigger signal. The trigger source is selected by setting the ADC TriggerSelect bits, ADTS in SFIOR.
ADIF ADC Interrupt Flag. This bit is set when an ADC conversion completes and theData Registers are updated. ADIF is cleared by hardware when executing thecorresponding interrupt handling vector otherwise it is cleared by writing alogical one to the flag
ADIE When this bit is written to one and the I-bit in SREG is set, the ADC ConversionComplete 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 321 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 00 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)
-
8/13/2019 1-Microcontroller Based System Design - Complete
33/55
-
8/13/2019 1-Microcontroller Based System Design - Complete
34/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 33
BitSet(ADCSRA, Bit(6)); //Start conversion again}
int main(void){
DDRA = 0x00; //PortA as input for ADC inputDDRD = 0xFF; //PortD as output for lower byte of Digital value
DDRB = 0xFF; //PortB as output for higher byte of Digital valueInitADC();sei(); //Enable global interruptwhile(1);
}
void InitADC(void){
BitSet(ADMUX, Bit(7)); //Internal 2.56V selected as VrefBitSet(ADMUX, Bit(6)); //Internal 2.56V selected as VrefBitClr(ADMUX, Bit(5)); //Right adjusted resultBitClr(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 ADCBitClr(ADCSRA, Bit(5)); //Disable Auto TriggerBitSet(ADCSRA, Bit(3)); //Enable ADC InterruptBitSet(ADCSRA, Bit(2)); //Prescaler = Fosc/128BitSet(ADCSRA, Bit(1)); //Prescaler = Fosc/128BitSet(ADCSRA, Bit(0)); //Prescaler = Fosc/128
BitSet(ADCSRA, Bit(6)); //Start Conversion//ADCSRA = 0xCF ; //Same settings as described above
}
Simulation:
-
8/13/2019 1-Microcontroller Based System Design - Complete
35/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 34
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.
Fornon-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
256 100 Non-inverted Mode Fast PWM
=255 0
256 100 Inverted Mode Fast PWM
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/WriteInitial Value
W0
RW0
RW0
RW0
RW0
RW0
RW0
RW0
-
8/13/2019 1-Microcontroller Based System Design - Complete
36/55
-
8/13/2019 1-Microcontroller Based System Design - Complete
37/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 36
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 determinedfrom the following formula:
=0
255 100 Non-inverted Mode Phase Correct PWM
=255 0
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 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
-
8/13/2019 1-Microcontroller Based System Design - Complete
38/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 37
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/WriteInitial Value
RW0
RW0
RW0
RW0
RW0
RW0
RW0
RW0
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)
ModeWGM
Timer/Counter Mode of Operation Top Top TypeUpdate of
OCR1xTOV Flag
Set on13 12 11 10
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)
-
8/13/2019 1-Microcontroller Based System Design - Complete
39/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 38
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*10020*256/100 = OCR0 + 151 = OCR0 + 1OCR0 = 50 = 0x32
So, we will load 0x32 in ORC0 in order to generate square wave, having 20% duty cycle*/
#includevoid main(void){
DDRB = 0xFF; //Make PortB as output to generate PWM on OC0 (PB3)OCR0 = 0x32; //to generate 20% duty cycleTCCR0 = 0x69; //Configure fast PWM, non-inverted, without prescaler
while(1);}
Simulation:
-
8/13/2019 1-Microcontroller Based System Design - Complete
40/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 39
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 theAVR and peripheral devices or between several AVR devices. The ATmega16 SPI includes thefollowing 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
-
8/13/2019 1-Microcontroller Based System Design - Complete
41/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 40
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 CPUclock 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. Aninterrupt 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 alsoset the SPIF Flag. SPIF is cleared by hardware when executing thecorresponding interrupt handling vector. Alternatively, the SPIF bit is cleared byfirst reading the SPI Status Register with SPIF set, then accessing the SPI DataRegister (SPDR).
WCOL Write Collision Flag: The WCOL bit is set if the SPI Data Register (SPDR) iswritten during a data transfer. The WCOL bit (and the SPIF bit) are cleared byfirst reading the SPI Status Register with WCOL set, and then accessing theSPI 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 SPIFbit in the SPSR Register is set and if the global interrupt enable bit in SREG isset.
SPE SPI Enable: When the SPE bit is written to one, the SPI is enabled. This bitmust be set to enable any SPI operations.
DORD Data Order: When the DORD bit is written to one, the LSB of the data word istransmitted first. When the DORD bit is written to zero, the MSB of the dataword is transmitted first.
MSTR Master/Slave Select: This bit selects Master SPI mode when written to one andSlave SPI mode when written logic zero. If SS is configured as an input and isdriven low while MSTR is set, MSTR will be cleared, and SPIF in SPSR willbecome set. The user will then have to set MSTR to re-enable SPI Mastermode.
-
8/13/2019 1-Microcontroller Based System Design - Complete
42/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 41
CPOL Clock Polarity: When this bit is written to one, SCK is high when idle. WhenCPOL is written to zero, SCK is low when idle
CPHA Clock Phase: The settings of the Clock Phase bit (CPHA) determine if data issampled on the leading (first) or trailing (last) edge of SCK.
SPR1:0 0 0 Fosc/ 40 1 Fosc/ 16
1 0 Fosc/ 641 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
-
8/13/2019 1-Microcontroller Based System Design - Complete
43/55
-
8/13/2019 1-Microcontroller Based System Design - Complete
44/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 43
DDRA=0xFF; //Make PortA as outputDDRB=(1
-
8/13/2019 1-Microcontroller Based System Design - Complete
45/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 44
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 thelines at Vcc potential.
Following figure shows the condition for a valid data:
-
8/13/2019 1-Microcontroller Based System Design - Complete
46/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 45
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 ninthSCL (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
-
8/13/2019 1-Microcontroller Based System Design - Complete
47/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 46
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:
-
8/13/2019 1-Microcontroller Based System Design - Complete
48/55
-
8/13/2019 1-Microcontroller Based System Design - Complete
49/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 48
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 theTwo-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 torecover 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 anyongoing 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 receivesthe same on Slave microcontroller. TWI feature of ATmega16 is used to complete the
task.*/
///////////////// CODE FOR MASTER/////////////////
#include
/////////////// Macros Definition/////////////////#define Bit(x) (0x01
-
8/13/2019 1-Microcontroller Based System Design - Complete
50/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 49
void i2c_init(void){
TWSR = 0x00; //Use zero prescalerTWBR = 123; //for SCL Freq = 1kHz and Fosc = 1MHzTWCR = 0x04; //Enable TWEN, TWI Module
}
void i2c_start(void){BitSet(TWCR, Bit(7)); //Clear TWINT, TWI Interrupt FlagBitSet(TWCR, Bit(5)); //Enable TWSTA, TWI Start ConditionBitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enablewhile(!(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 regBitSet(TWCR, Bit(7)); //Clear TWEN, TWI Interrupt FlagBitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enablewhile(!(BitGet(TWCR, Bit(7))));//Stay till data transmitted
}
void i2c_stop(void){
BitSet(TWCR, Bit(7)); //Clear TWINT, TWI Interrupt FlagBitSet(TWCR, Bit(4)); //Enable TWSTA, TWI Stop ConditionBitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enablewhile(!(BitGet(TWCR, Bit(7))));//Stay till stop condition transmitted
}
void main(void){
i2c_init(); //initialize TWI modulei2c_start(); //transmit start condition
i2c_write(0b01010101); //call the address of slave 0x55i2c_write('A'); //Transmit ASCII of character Ai2c_stop(); //Transmit start conditionwhile(1);
}
///////////////// CODE FOR SLAVE/////////////////
#include
/////////////// Macros Definition/////////////////#define Bit(x) (0x01
-
8/13/2019 1-Microcontroller Based System Design - Complete
51/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 50
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 FlagBitSet(TWCR, Bit(6)); //Enable TWEA, Send AcknowledgeBitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enable
}else
{BitSet(TWCR, Bit(7)); //Clear TWINT, TWI Interrupt FlagBitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enable
}while(!(BitGet(TWCR, Bit(7)))); //Stay till data byte receivedreturn (TWDR);
}
void main(void){
DDRA = 0xFF;i2c_InitSlave(); //initialize TWI modulei2c_listen(); //transmit start conditionPORTA = i2c_receive(1); //Receive only one bytewhile(1);
}
Simulation:
-
8/13/2019 1-Microcontroller Based System Design - Complete
52/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 51
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.
-
8/13/2019 1-Microcontroller Based System Design - Complete
53/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 52
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 supplythe 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. controlpulse is 2ms */
-
8/13/2019 1-Microcontroller Based System Design - Complete
54/55
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 53
#include #include
/*CALCULATION:
We will use mode 14 (as per datasheet of ATmega16) to generate variable top PWMwith 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))-1where N is prescaler
Freq CPU = 1MHz
Prescaler = 16Freq PWM = 50HzTop = (1MHz / (50Hz x 8))-1Top = 2499
Position of Servo Motor against different pulse widths5% 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) * 1005 / 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 + 1OCR1x = 249
*/
void main(void){
unsigned int x;//Configure Timer1 registersTCCR1A |= (1
-
8/13/2019 1-Microcontroller Based System Design - Complete
55/55
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