1-Microcontroller Based System Design - Complete
1-Microcontroller Based System Design - Complete
Microcontroller Based
System Design
Prepared By: Engr. Muhammad Muzammil
Revised on: 27th August, 2013
Name:
Reg No.
Section:
Microcontroller Based System Design
LIST OF EXPERIMENTS
S. # Title Page #
1. I/O Ports Programming & LED Interfacing 2
4. Interrupt Programming 14
6. LCD Interfacing 25
7. ADC Programming 29
8. PWM Programming 34
9. SPI Programming 39
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 1
Microcontroller Based System Design
Arduino Overview:
Arduino is a prototype platform (open-source) based on an easy-to-use hardware and
software. It consists of a circuit board, which can be programed (referred to as a
microcontroller) and a ready-made software called Arduino IDE (Integrated
Development Environment), which is used to write and upload the computer code to the
physical board.
The key features are:
Arduino boards are able to read analog or digital input signals from different
sensors and turn it into an output such as activating a motor, turning LED on/off,
connect to the cloud and many other actions.
You can control your board functions by sending a set of instructions to the
microcontroller on the board via Arduino IDE (referred to as uploading software).
Unlike most previous programmable circuit boards, Arduino does not need an
extra piece of hardware (called a programmer) in order to load a new code onto
the board. You can simply use a USB cable.
Additionally, the Arduino IDE uses a simplified version of C++, making it easier
to learn to program.
Finally, Arduino provides a standard form factor that breaks the functions of the
micro-controller into a more accessible package
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 2
Microcontroller Based System Design
Digital I/O pins – input and output pins (0-13) of which 6 of them (3, 5, 6, 9, 10
and 11) also provide PWM (Pulse Width Modulated) output by using the
analogWrite() function. Pins (0 (RX) and 1 (TX)) are also used to transmit and
receive serial data.
ICSP Header – pins for “In-Circuit Serial Programming” which is another method
of programming.
Power Pins – pins that can be used to supply a circuit with values VIN (voltage
from DC Jack), 3.3V and 5V.
Reset Button – a button that is pressed whenever you need to restart the
sketch programmed in the board.
USB port – allows the user to connect with a USB cable the board to a PC to
upload sketches or provide a voltage supply to the board. This is also used for
serial communication through the serial monitor from the Arduino software.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 3
Microcontroller Based System Design
Let us start with the Structure. Software structure consist of two main functions:
void setup ( )
The setup() function is called when a sketch starts. Use it to initialize the
variables, pin modes, start using libraries, etc. The setup function will only run
once, after each power up or reset of the Arduino board.
void loop ( )
After creating a setup() function, which initializes and sets the initial values, the
loop() function does precisely what its name suggests, and loops consecutively,
allowing your program to change and respond. Use it to actively control the
Arduino board
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 4
Microcontroller Based System Design
Write a program to toggle LEDs connected to Port B with delay of one second
Void setup( )
DDRB= 0xFF;
Void loop( )
PORTB = 0xFF;
delay(1000);
PORTB =0x00;
delay(1000);
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 5
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 6
Microcontroller Based System Design
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 7
Microcontroller Based System Design
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.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 8
Microcontroller Based System Design
// a
// _____
// f | g | b
// |_____|
// e | | c dot
// |_____| .
// d
//________________________________________
// | No. | e d c dot g f a b |
// | 0 | 1 1 1 0 0 1 1 1 = 0xE7 |
// | 1 | 0 0 1 0 0 0 0 1 = 0x21 |
// | 2 | 1 1 0 0 1 0 1 1 = 0xCB |
// | 3 | 0 1 1 0 1 0 1 1 = 0x6B |
// | 4 | 0 0 1 0 1 1 0 1 = 0x2D |
// | 5 | 0 1 1 0 1 1 1 0 = 0x6E |
// | 6 | 1 1 1 0 1 1 1 0 = 0xEE |
// | 7 | 0 0 1 0 0 0 1 1 = 0x23 |
// | 8 | 1 1 1 0 1 1 1 1 = 0xEF |
// | 9 | 0 1 1 0 1 1 1 1 = 0x6F |
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 9
Microcontroller Based System Design
Simulation:
Home Task:
Extend the above circuit to four 7-segment displays. Value of least significant 7 segment
display is incremented after every 125 milliseconds (approx).
Attach three push buttons with three MSBs of PortB. When Switch 1 (PortB.7) is
pressed, counting stops and current value is retained on the 7-segment displays
constantly. Now by pressing Switch 2 (PortB.6), value displayed on 7-segment displays
is incremented and by pressing switch 3 (PortB.5), value on 7-segment displays is
decremented. Now again by pressing Switch 1, counting is started from the
new/changed value on 7-segment displays.
Note: Define, declare and use the functions, UpCount(), DownCount(), SetCount() in
your code.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 10
Microcontroller Based System Design
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.
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.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 11
Microcontroller Based System Design
FOC0 Force Output Compare: FOC0 bit is only active when the WGM00:1
bits specifies a non-PWM mode. This bit is always read as zero. When
this bit is set, and a compare with
WGM00 WGM01 Timer Mode 0 Selector Bits (Four modes available)
0 0 Normal Mode
0 1 CTC (Clear Timer on Compare Match) Mode
1 0 PWM, Phase Correct Mode
1 1 Fast PWM
COM01 : COM00 Compare Output Mode: These bits control waveform generation, if
CTC mode is selected through WGM00-01 bits then:
0 0 Normal mode operation
0 1 Toggle OC0 (PB3, Pin 4) on compare match
1 0 Clear OC0 on compare match
1 1 Set OC0 on compare match
CS02:00 D2 D1 D0 Timer 0 Clock Source Selector
0 0 0 No clock source (Timer/Counter stopped)
0 0 1 clk (No Prescaling)
0 1 0 clk / 8
0 1 1 clk / 64
1 0 0 clk / 256
1 0 1 clk / 1024
1 1 0 External clock on T0 (PB0) pin. Clock on falling edge
1 1 1 External clock on T0 (PB0) pin. Clock on rising edge
Bit # 7 6 5 4 3 2 1 0
Bit Name OCF2 TOV2 ICF1 OCF1A OCF1B TOV1 OCF0 TOV0
Read/Write W RW RW RW RW RW RW RW
Initial Value 0 0 0 0 0 0 0 0
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 12
Microcontroller Based System Design
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.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 13
Microcontroller Based System Design
//This program generates 5Hz square wave on PA0 with a duty cycle of 50%. ON time
// is 100ms and OFF time is also 100ms.
#include<avr/io.h>
#include<util/delay.h>
//Macros definition
#define BitGet(p,m) ((p) & (m))
#define BitSet(p,m) ((p) |= (m))
#define BitFlip(p,m) ((p) ^= (m))
#define Bit(x) (0x01 << (x))
void main(void)
{
DDRA = 0xFF; //Make PortA output
BitSet(PORTA, Bit(0)); //Initially set PA0
while(1)
{
BitFlip(PORTA, Bit(0)); //Toggle PA0
TimerDelay(); //Generates delay of about 100ms
}
}
/* delay calculation
For a clock generation of 5Hz (200ms), timer should be overflowed twice, so:
Timer overflow @ = 200ms / 2 = 100ms (0.1s high, 0.1s low)
Crystal Clock = 1MHz
Prescaler used = 1024
Timer clock = 1MHz / 1024 = 976.5625 Hz
Timer Period = 1/976.5625 = 1024us
Timer Value = 0.1s / 1024us = 97.65625 = 98 (approx) */
void TimerDelay(void)
{
TCNT0 = 0x9F; // (256+1)-98 = 159 = 0x9F
TCCR0 = 0x05; //Timer0 ON, clk/1024 prescaler, Normal Mode
while(!BitGet(TIFR, Bit(0))); // Wait for timer0 overflow & TOV0 flag is raised
TCCR0 = 0x00; //Stop Timer
BitSet(TIFR, Bit(0)); //Clear TOV0
}
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 14
Microcontroller Based System Design
Simulation:
//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>
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 15
Microcontroller Based System Design
Simulation:
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.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 16
Microcontroller Based System Design
Introduction:
There are two methods by which a microcontroller can serve a device
Vector
Address Source Interrupt Definition
No.
External Pin, Power-on Reset, Brown-out Reset,
1 $000 Reset
Watchdog Reset, and JTAG AVR Reset
2 $002 INT0 External Interrupt Request 0
3 $004 INT1 External Interrupt Request 1
4 $006 TIMER2 COMP Timer/Counter2 Compare Match
5 $008 TIMER2 OVF Timer/Counter2 Overflow
6 $00A TIMER1 CAPT Timer/Counter1 Capture Event
7 $00C TIMER1 COMPA Timer/Counter1 Compare Match A
8 $00E TIMER1 COMPB Timer/Counter1 Compare Match B
9 $010 TIMER1 OVF TIMER1 OVF Timer/Counter1 Overflow
10 $012 TIMER0 OVF Timer/Counter0 Overflow
11 $014 SPI, STC Serial Transfer Complete
12 $016 USART, RXC Rx Complete
13 $018 USART, UDRE USART Data Register Empty
14 $01A USART, TXC USART, Tx Complete
15 $01C ADC ADC Conversion Complete
16 $01E EE_RDY EEPROM Ready
17 $020 ANA_COMP Analog Comparator
18 $022 TWI Two-wire Serial Interface
19 $024 INT2 External Interrupt Request 2
20 $026 TIMER0 COMP Timer/Counter0 Compare Match
21 $028 SPM_RDY Store Program Memory Ready
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 17
Microcontroller Based System Design
Above table shows the interrupt sources and their interrupt vectors for AVR ATmega16. Memory
locations from 0002 to 0028 locations are reserve for interrupt vectors. Each interrupt has 2
words (4 bytes) of memory space for its ISR. For example, 0012 to 0014 memory space is set
aside for Timer0 overflow ISR.
Usually ISR cannot fit into 4-bytes memory space. So a JMP instruction is kept at the vector
address from where ISR jumps to another location where rest of the code of ISR can be written.
At the end of each ISR, RETI (Return from Interrupt) instruction is placed which gives the
control back to the location from where it was interrupted.
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
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 18
Microcontroller Based System Design
Bit # 7 6 5 4 3 2 1 0
Bit Name INT1 INT0 INT2 - - - IVSEL IVCE
INT0 and INT1 can be programmed to trigger on low level, rising edge, falling edge or both
edges through MCUCR (MCU Control Register). Whereas, INT2 can only be programmed to
trigger on falling or rising edge through MCUCSR (MCU Control and Status Register).
If an interrupt is programmed for edge trigger mode, the pulse must be 1 instruction cycle to
ensure that the transition is seen by microcontroller. If an interrupt is programmed for level
trigger, the pin must be held low for at least 5 machine cycles to cause an interrupt.
Bit # 7 6 5 4 3 2 1 0
Bit Name SE SM2 SM1 SM0 ISC11 ISC10 ISC01 ISC00
Bit # 7 6 5 4 3 2 1 0
Bit Name JTD ISC2 - JTRF WDRF BORF EXTRF PORF
ISC2 Description
0 The falling edge of INT2 generates an interrupt request
1 The rising edge of INT2 generates an interrupt request
MCUCSR (MCU Control and Status Register)
GIFR (General Interrupt Flag Register) has external interrupt flags. When an external interrupt is
occurs, corresponding flag of that external interrupt is raised. When microcontroller jumps of the
interrupt vector table, flag is automatically cleared or we can clear the flag by writing high on it.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 19
Microcontroller Based System Design
Bit # 7 6 5 4 3 2 1 0
Bit Name INTF1 INTF0 INTF2 - - - - -
INTF1 When an external interrupt occurs, its corresponding flag bit in GIFR is set.
INTF0 When AVR jumps to its ISR, this flag is cleared by AVR. For level triggering, pin
INTF2 must be hold for at least 5 instruction cycles to be recognized.
/*
This program generates a square wave of 5Hz (200ms) on PortA, Bit 0 using Timer0 CTC
interrupt. Moreover, at the same time, using External Hardware Interrupt INT2 is
configured on falling edge. Upon each INT2 falling edge interrupt, value of PortD is
incremented.
*/
#include<avr/io.h>
#include<avr/interrupt.h>
//Macros Definition
#define BitSet(p,m) ((p) |= (m))
#define BitClear(p, m) ((p) &= ~(m))
#define BitFlip(p,m) ((p) ^= (m))
#define Bit(x) (0x01 << (x))
int main(void)
{
DDRD = 0xFF; //Make PortD output
BitSet(DDRA, Bit(0)); //Make PA0 output
BitClear(DDRB, Bit(2)); //Make PB2 as input for INT2
BitSet(PORTB, Bit(2)); //Internally pull-up PB2
BitSet(TIMSK, Bit(1)); //Enable OC0IE bit to enable Timer0 Compare Mode interrupt
BitSet(GICR, Bit(5)); //Enable INT2 bit to enable External Interrupt 2
BitClear(MCUCSR, Bit(6));//Configure Falling edge triggered INT2 interrupt
sei(); //Enable Global Interrupt
OCR0 = 98; //98 calculated in the last lab for 0.1 seconds time
TCCR0 = 0x0D; //0000 1101, CTC Mode, Crystal Clock, 1024 prescaler
//Interrupt Service Routines (ISRs) of Timer0 CTC Mode & External Interrupt INT2
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 20
Microcontroller Based System Design
Simulation:
Home Task:
Repeat the home task of Lab-3. At the same time, interface a push button with external
interrupt0. When this button is pressed (external interrupt 0 is invoked), square wave
generation should be stopped. When this button is pressed again, square wave
generation should start again.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 21
Microcontroller Based System Design
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.
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.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 22
Microcontroller Based System Design
UCSRA: USART Control Status Register A: For controlling serial communication in AVR
UCSRB: USART Control Status Register B: For controlling serial communication in AVR
UCSRC: USART Control Status Register C: For controlling serial communication in AVR
UBRR: USART Baud Rate Register: Value written in this register determines the baud rate
𝐹𝑜𝑠𝑐
𝐷𝑒𝑠𝑖𝑟𝑒𝑑 𝐵𝑎𝑢𝑑 𝑅𝑎𝑡𝑒 =
16(𝑋 + 1)
or
𝐹𝑜𝑠𝑐
𝑋= −1
16(𝐷𝑒𝑠𝑖𝑟𝑒𝑑 𝐵𝑎𝑢𝑑 𝑅𝑎𝑡𝑒)
Where X is the value loaded in the UBRR for a specific desired baud rate. Above
calculation will be true for default setting upon reset.
RXC USART Receive Complete: When a complete byte is received, this flag is set.
Cleared when buffer is empty. This flag is also used to generate receive complete
interrupt.
TXC USART Transmit Complete: When a complete byte is transmitted, this flag is set.
Cleared when buffer is empty. This flag is also used to generate transmit complete
interrupt. Automatically cleared when interrupt is executed.
UDRE USART Data Register Empty: This flag is set when transmit data buffer is empty
and it is ready to receive new data. If this flag is cleared, data should not be written
into UDR. This flag is also used to generate data register empty interrupt.
FE Framing Error: This bit is set, if there is error in the frame of next received byte.
Frame error is generated when the first stop bit of next character in the received
buffer is zero.
DOR Data Overrun: A data overrun occurs when the received data buffer and received
shift register are full, and a new start bit is detected. Set flag enables data overrun.
PE Parity Error: This bit is set if parity checking is enabled (UPM1 = 1) and the next
character in the receive buffer has a parity error.
U2X Double the USART Transmission Speed: Setting this bit will double the baud
rate for asynchronous communication.
MPCM Multiprocessor Communication Mode: This enables the multi-processor
communication mode. The MPCM is not discussed in this lab
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 23
Microcontroller Based System Design
FE, PE and DOR are valid until UDR is read. Set these to zero for transmission
For crystal frequency of 1MHz and 8MHz, the most commonly used baud rates for
asynchronous operation can be generated by using the UBRR settings shown in the
following table:
RXCIE USART Receive Complete Interrupt Enable: Setting this bit enables the receive
complete interrupt
TXCIE USART Transmit Complete Interrupt Enable: Setting this bit enables the transmit
complete interrupt
UDRIE USART Data Register Empty Interrupt Enable: Setting this bit enables the data
register empty interrupt
RXEN USART Receive Enable: Setting this bit enables USART receiver
TXEN USART Transmit Enable: Setting this bit enables USART transmitter
UCSZ2 USART Character Size: See bit USCZ0 and USCZ1 in UCSRC
RXB8 Receive data bit 8: When using serial frames with nine data bits, the ninth
received bit of every frame is placed in this RXB8.
TXB8 Transmit data bit 8: When using serial frames with nine data bits, the ninth
transmitted bit of every frame is placed in this TXB8.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 24
Microcontroller Based System Design
URSEL Register Select: Setting this bit enables to change the contents of UCSRC
register else, UBRRH is selected
UMSEL Mode Select: Setting this bit selects Asynchronous mode, else synchronous
mode
USBS Stop Bit Select: Setting this bit will add 2 stop bits in frame else 1 stop bit
UCSZ1:0 Character Size: Combined with Bit2 (UCSZ2) selects the different data bits in a
frame
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 25
Microcontroller Based System Design
#include<avr/io.h>
#include<avr/interrupt.h>
//Macros Definition
#define BitSet(p,m) ((p) |= (m))
#define BitClr(p, m) ((p) &= ~(m))
#define Bit(x) (0x01 << (x))
int main(void)
{
DDRA = 0xFF; //PortA as output
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 26
Microcontroller Based System Design
Simulation:
Home Task:
Through serial port, transmit your name from the serial port to AVR and AVR should
return back first four digits of your registration number. Use crystal oscillator of 1MHz.
Set the baud rate to the nearest available range as per the following formula:
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 27
Microcontroller Based System Design
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).
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 28
Microcontroller Based System Design
Following table shows some useful command list which is generally required to interface
and program the microcontroller with LCD.
00 01 02 03 – 04 05 06 07 80 81 82 83 – 84 85 86 87
1
08 09 10 11 – 12 13 14 15 88 89 8A 8B – 8C 8D 8E 8F
00 01 02 03 – 04 05 06 07 C0 C1 C2 C3 – C4 C5 C6 C7
2
08 09 10 11 – 12 13 14 15 C8 C9 CA CB – CC CD CE CF
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 29
Microcontroller Based System Design
//Macros Definition
#define BitSet(p,m) ((p) |= (m))
#define BitClr(p, m) ((p) &= ~(m))
#define BitFlip(p,m) ((p) ^= (m))
#define Bit(x) (0x01 << (x))
void LCD_init();
void cmd_4b(unsigned char);
void data_4b(unsigned char);
void LCDcmd(unsigned char);
void LCDdata(unsigned char);
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 30
Microcontroller Based System Design
Simulation:
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 31
Microcontroller Based System Design
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.
𝑉𝑖𝑛 × 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.
where Vpos and Vneg are the two differential input channels and the Gain can be selected
as 1x, 10x and 200x from ADMUX register.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 32
Microcontroller Based System Design
Bit # 7 6 5 4 3 2 1 0
Bit Name REFS1 REFS0 ADLAR MUX4 MUX3 MUX2 MUX1 MUX0
ADLAR ADC Left Adjusted Result. When this bit is set, ADCL contains only two LSBs of
the result at position D7 and D6. Remaining bits are not used
MUX4 : 0 Analog channel and gain selection bits. See following table for details
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 33
Microcontroller Based System Design
Bit # 7 6 5 4 3 2 1 0
Bit Name ADEN ADSC ADATE ADIF ADIE ADPS2 ADPS1 ADPS0
Bit # 7 6 5 4 3 2 1 0
Bit Name ADTS2 ADTS1 ADTS0 - ACME PUD PSR2 PSR10
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 34
Microcontroller Based System Design
/* 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>
void InitADC(void);
ISR(ADC_vect)
{
PORTD = ADCL;
PORTB = ADCH;
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 35
Microcontroller Based System Design
int main(void)
{
DDRA = 0x00; //PortA as input for ADC input
DDRD = 0xFF; //PortD as output for lower byte of Digital value
DDRB = 0xFF; //PortB as output for higher byte of Digital value
InitADC();
sei(); //Enable global interrupt
while(1);
}
void InitADC(void)
{
BitSet(ADMUX, Bit(7)); //Internal 2.56V selected as Vref
BitSet(ADMUX, Bit(6)); //Internal 2.56V selected as Vref
BitClr(ADMUX, Bit(5)); //Right adjusted result
BitClr(ADMUX, Bit(4)); //Single ended (GND as common ground)
BitClr(ADMUX, Bit(3)); //non-differential input on ADC0 channel (PA0, Pin No. 40)
BitClr(ADMUX, Bit(2)); //
BitClr(ADMUX, Bit(1)); //
BitClr(ADMUX, Bit(0)); //
//ADMUX = 0xC0; //Same settings as given above
Simulation:
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 36
Microcontroller Based System Design
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.
In Fast PWM, the TCNT0 counts like it does in Normal Mode. After the timer is started, it starts
to count up. Whenever it rolls over from its Top (0xFF in Timer0) to 0x00, TOV0 flag is raised. It
can be selected by using COM01:00 bits of TCCR0 whether to set or clear the OC0 pin after the
TOV0 flag is raised. While counting from Bottom to Top, compare match occurs when TCNT0
matches OCR0 and on the compare match, OC0 pin can be programmed to set or clear.
For non-inverted Fast PWM mode, upon compare match, OC0 pin clears and upon Top (0xFF)
of TCNT0, OC0 pin sets. For inverted Fast PWM mode, upon compare match, OC0 pins sets
and upon Top (0xFF) of TCNT0, OC0 pin clears. Both of these modes of Fast PWM can be
understood from the Fig 8.1.
Value to be loaded in OCR0 to generate the PWM of required duty cycle can be determined
from the following formula:
𝑂𝐶𝑅0 + 1
𝐷𝑢𝑡𝑦 𝐶𝑦𝑐𝑙𝑒 = × 100 Non-inverted Mode Fast PWM
256
255 − 𝑂𝐶𝑅0
𝐷𝑢𝑡𝑦 𝐶𝑦𝑐𝑙𝑒 = × 100 Inverted Mode Fast PWM
256
WGM01:00 bits of TCCR0 register are used to select the different modes of timer.
Bit # 7 6 5 4 3 2 1 0
Bit Name FOC0 WGM00 COM01 COM00 WGM01 CS02 CS01 CS00
Read/Write W RW RW RW RW RW RW RW
Initial Value 0 0 0 0 0 0 0 0
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 37
Microcontroller Based System Design
FOC0 Force Output Compare: FOC0 bit is only active when the WGM00:1
bits specifies a non-PWM mode.
WGM00 WGM01 Timer Mode 0 Selector Bits (Four modes available)
0 0 Normal Mode
0 1 CTC (Clear Timer on Compare Match) Mode
1 0 PWM, Phase Correct Mode
1 1 Fast PWM
COM01 : COM00 Compare Output Mode: used to select the following operation if Fast
PWM is selected through WGM01:00:
0 0 Disconnect, Normal port operation, OC0 disconnected
0 1 Reserved
1 0 Non-inverted, Clear OC0 on compare match, set OC0 at Top
1 1 Inverted, Set OC0 on compare match, clearOC0 on Top
In Phase Correct PWM Mode, the TCNT0 goes up and down like a yo-yo. After the timer is
started, it starts to count up and after reaching Top, it counts downward. Whenever it reaches to
0x00, TOV0 flag is raised. TCNT0 meets the OCR0 two times, one while counting upward and
second while counting downward. It can be selected by using COM01:00 bits of TCCR0
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 38
Microcontroller Based System Design
whether to set or clear the OC0 pin after compare match is occurred while counting upward.
Similarly, while counting downward, on the compare match, OC0 pin can be programmed to set
or clear. In non-inverted phase correct mode, OC0 pin is cleared when compare match occurs
while TCNT0 is counting upward and set OC0 pin when compare match occurs while TCNT0 is
counting downward. Reverse is the case from Inverted phase correct PWM. Both of these
modes of Phase Correct PWM can be understood from the Fig 8.2.
Value to be loaded in OCR0 to generate the PWM of required duty cycle can be determined
from the following formula:
𝑂𝐶𝑅0
𝐷𝑢𝑡𝑦 𝐶𝑦𝑐𝑙𝑒 = × 100 Non-inverted Mode Phase Correct PWM
255
255 − 𝑂𝐶𝑅0
𝐷𝑢𝑡𝑦 𝐶𝑦𝑐𝑙𝑒 = × 100 Inverted Mode Phase Correct PWM
255
In TCCR0, Phase Correct PWM Mode can be selected by WGM01:00 = 01. For Phase Correct
PWM Mode, COM01:00 bits of TCCR0 performs the following operation:
0 1 Reserved
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 39
Microcontroller Based System Design
As Timer2 is also 8-bit timer, therefore it works similar to Timer0. The differences are the
register names, output pin and the prescaler of TCCRx register. For Timer0 and Timer2 the Top
is fixed (0xFF).
Timer1 is a 16-bit timer. Modes of Timer1 can be selected from TCCR1B TCCR1A registers.
Details of PWM generation through Timer1 are beyond the scope of this lab. However, the basic
principle is same as discussed earlier.
Bit # 7 6 5 4 3 2 1 0
Bit Name ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10
Read/Write RW RW RW RW RW RW RW RW
Initial Value 0 0 0 0 0 0 0 0
ICES1 D6 Setting this bit enables the input capture on falling edge
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 40
Microcontroller Based System Design
So, we will load 0x32 in ORC0 in order to generate square wave, having 20% duty cycle
*/
#include<AVR\io.h>
void main(void)
{
DDRB = 0xFF; //Make PortB as output to generate PWM on OC0 (PB3)
OCR0 = 0x32; //to generate 20% duty cycle
TCCR0 = 0x69; //Configure fast PWM, non-inverted, without prescaler
while(1);
}
Simulation:
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 41
Microcontroller Based System Design
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:
Following figure shows the interconnection between two SPI devices. The system consists of
communication by pulling low the SS pin of desired slave device. SCK is the clock signal which
is generated by Master device. Data between both the devices is exchanged by SCK clock rate.
Data is always shifted from Master to Slave on MOSI (Master Out, Slave In) and from Slave to
Master on MISO (Master In, Slave Out) pin. Master will pull the SS pin high after transmission of
data.
When device is configured as Master, SPI has no control on SS pin. This pin must be controlled
by software. Before start of transmission from Mater to Slave, SS pin must be kept low. After
shifting one byte, the SPI clock generator stops, setting the end of Transmission Flag (SPIF). If
the SPI Interrupt Enable bit (SPIE) in the SPCR Register is set, an interrupt is requested. The
Master may continue to shift the next byte by writing it into SPDR, or signal the end of packet by
pulling high the Slave Select, SS line. The last incoming byte will be kept in the Buffer Register
for later use.
When configured as a Slave, the SPI interface will remain sleeping with MISO tri-stated as long
as the SS pin is driven high. In this state, software may update the contents of the SPI Data
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 42
Microcontroller Based System Design
Register, but the data will not be shifted out by incoming clock pulses on the SCK pin until the
SS pin is driven low. As one byte has been completely shifted, the end of Transmission Flag,
SPIF is set. If the SPI Interrupt Enable bit (SPIE) is set, an interrupt is requested. The Slave
may continue to place new data to be sent into SPDR before reading the incoming data. The
last incoming byte will be kept in the Buffer Register for later use.
For Slave, minimum low and high period of the clock on SCK pin should be longer than 02 CPU
clock cycles.
Bit # 7 6 5 4 3 2 1 0
Bit Name SPIF WCOL - - - - - SPI2X
SPIF SPI Interrupt Flag: When a serial transfer is complete, the SPIF Flag is set. An
interrupt is generated if SPIE in SPCR is set and global interrupts are enabled.
If SS is an input and is driven low when the SPI is in Master mode, this will also
set the SPIF Flag. SPIF is cleared by hardware when executing the
corresponding interrupt handling vector. Alternatively, the SPIF bit is cleared by
first reading the SPI Status Register with SPIF set, then accessing the SPI Data
Register (SPDR).
WCOL Write Collision Flag: The WCOL bit is set if the SPI Data Register (SPDR) is
written during a data transfer. The WCOL bit (and the SPIF bit) are cleared by
first reading the SPI Status Register with WCOL set, and then accessing the
SPI Data Register.
SPI2X Double SPI Speed: When this bit is written logic one the SPI speed (SCK
Frequency) will be doubled when the SPI is in Master mode
Bit # 7 6 5 4 3 2 1 0
Bit Name SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0
SPIE SPI Interrupt Enable: This bit causes the SPI interrupt to be executed if SPIF
bit in the SPSR Register is set and if the global interrupt enable bit in SREG is
set.
SPE SPI Enable: When the SPE bit is written to one, the SPI is enabled. This bit
must be set to enable any SPI operations.
DORD Data Order: When the DORD bit is written to one, the LSB of the data word is
transmitted first. When the DORD bit is written to zero, the MSB of the data
word is transmitted first.
MSTR Master/Slave Select: This bit selects Master SPI mode when written to one and
Slave SPI mode when written logic zero. If SS is configured as an input and is
driven low while MSTR is set, MSTR will be cleared, and SPIF in SPSR will
become set. The user will then have to set MSTR to re-enable SPI Master
mode.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 43
Microcontroller Based System Design
CPOL Clock Polarity: When this bit is written to one, SCK is high when idle. When
CPOL is written to zero, SCK is low when idle
CPHA Clock Phase: The settings of the Clock Phase bit (CPHA) determine if data is
sampled on the leading (first) or trailing (last) edge of SCK.
SPR1:0 0 0 Fosc / 4
0 1 Fosc / 16
1 0 Fosc / 64
1 1 Fosc / 128
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:
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 44
Microcontroller Based System Design
C Code for data transfer between two ATmega16 using SPI feature of AVR:
/*
This program transmits a character from first ATmega16 microcontroller and receives
the same on other microcontroller. SPI feature of ATmega16 is used to complete the
task.
*/
#define MOSI 5
#define MISO 6
#define SCK 7
#define SS 4
void main(void)
{
unsigned char x=0;
while(1)
{
BitClr(PORTB, Bit(SS)); //Enable Slave Select Pin
SPDR=x; //Load SPI Data Register for transmission
while(!(BitGet(SPSR, Bit(7)))); //wait until SPI Interrupt Flag is raised
BitSet(PORTB, Bit(SS)); //Disable Slave Select Pin
_delay_ms(500);
x++;
}
}
#include<avr/io.h>
#define MOSI 5
#define MISO 6
#define SCK 7
#define SS 4
void main(void)
{
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 45
Microcontroller Based System Design
Simulation:
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 46
Microcontroller Based System Design
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.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 47
Microcontroller Based System Design
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.
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.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 48
Microcontroller Based System Design
STOP conditions, while the receiver is responsible for acknowledging the reception. An
Acknowledge (ACK) is signaled by the receiver pulling the SDA line low during the ninth SCL
cycle. If the receiver leaves the SDA line high, a NACK is signaled. When the receiver has
received the last byte, or for some reason cannot receive any more bytes, it should inform the
transmitter by sending a NACK after the final byte.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 49
Microcontroller Based System Design
TWI Registers:
As shown in the above block diagram, TWI module of AVR has following registers:
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 # 7 6 5 4 3 2 1 0
Bit Name TWS7 TWS6 TWS5 TWS4 TWS3 - TWPS1 TWPS0
TWS7:3 TWS: TWI Status: These five bits show the status of TWI control and bus. For
more details, see datasheet
Bit # 7 6 5 4 3 2 1 0
Bit Name TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE
TWINT This bit is set by hardware when the TWI has finished its current job and expects
application software response. If the I-bit in SREG and TWIE in TWCR are set, the
MCU will jump to the TWI Interrupt Vector. While the TWINT Flag is set, the SCL low
period is stretched. The TWINT Flag must be cleared by software by writing a logic
one to it. Note that this flag is not automatically cleared by hardware when executing
the interrupt routine. Also note that clearing this flag starts the operation of the TWI, so
all accesses to the TWI Address Register (TWAR), TWI Status Register (TWSR), and
TWI Data Register (TWDR) must be complete before clearing this flag.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 50
Microcontroller Based System Design
TWEA The TWEA bit controls the generation of the acknowledge pulse. If the TWEA bit is
written to one, the ACK pulse is generated on the TWI bus if the following conditions
are met:
1. The device’s own Slave address has been received.
2. A general call has been received, while the TWGCE bit in the TWAR is set.
3. A data byte has been received in Master Receiver or Slave Receiver mode.
By writing the TWEA bit to zero, the device can be virtually disconnected from the
Two-wire Serial Bus temporarily. Address recognition can then be resumed by writing
the TWEA bit to one again.
TWSTA The application writes the TWSTA bit to one when it desires to become a Master on
the Two-wire Serial Bus. The TWI hardware checks if the bus is available, and
generates a START condition on the bus if it is free. However, if the bus is not free,
the TWI waits until a STOP condition is detected, and then generates a new START
condition to claim the bus Master status. TWSTA must be cleared by software when
the START condition has been transmitted.
TWSTO Writing the TWSTO bit to one in Master mode will generate a STOP condition on the
Two-wire Serial Bus. When the STOP condition is executed on the bus, the TWSTO
bit is cleared automatically. In Slave mode, setting the TWSTO bit can be used to
recover from an error condition. This will not generate a STOP condition, but the TWI
returns to a well-defined unaddressed Slave mode and releases the SCL and SDA
lines to a high impedance state.
TWWC The Write collusion bit is set when attempting to write to the TWI Data Register TWDR
when TWINT is low. This flag is cleared by writing the TWDR Register when TWINT is
high.
TWEN The TWEN bit enables TWI operation and activates the TWI interface. When TWEN is
written to one, the TWI takes control over the I/O pins connected to the SCL and SDA
pins, enabling the slew-rate limiters and spike filters. If this bit is written to zero, the
TWI is switched off and all TWI transmissions are terminated, regardless of any
ongoing operation.
TWIE When this bit is written to one, and the I-bit in SREG is set, the TWI interrupt request
will be activated for as long as the TWINT Flag is high.
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.
*/
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 51
Microcontroller Based System Design
void i2c_init(void)
{
TWSR = 0x00; //Use zero prescaler
TWBR = 123; //for SCL Freq = 1kHz and Fosc = 1MHz
TWCR = 0x04; //Enable TWEN, TWI Module
}
void i2c_start(void)
{
BitSet(TWCR, Bit(7)); //Clear TWINT, TWI Interrupt Flag
BitSet(TWCR, Bit(5)); //Enable TWSTA, TWI Start Condition
BitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enable
while(!(BitGet(TWCR, Bit(7)))); //Stay till start condition transmitted
}
void i2c_stop(void)
{
BitSet(TWCR, Bit(7)); //Clear TWINT, TWI Interrupt Flag
BitSet(TWCR, Bit(4)); //Enable TWSTA, TWI Stop Condition
BitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enable
while(!(BitGet(TWCR, Bit(7)))); //Stay till stop condition transmitted
}
void main(void)
{
i2c_init(); //initialize TWI module
i2c_start(); //transmit start condition
i2c_write(0b01010101); //call the address of slave 0x55
i2c_write('A'); //Transmit ASCII of character A
i2c_stop(); //Transmit start condition
while(1);
}
void i2c_InitSlave(void)
{
TWCR = 0x04; //Enable TWEN, TWI Module
TWAR = 0b01010101; //Set Slave address
BitSet(TWCR, Bit(7)); //Clear TWINT, TWI Interrupt Flag
BitSet(TWCR, Bit(6)); //Enable TWEA, Send Acknowledge
BitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enable
}
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 52
Microcontroller Based System Design
void i2c_listen(void)
{
while(!(BitGet(TWCR, Bit(7)))); //Stay till data transmitted
}
void main(void)
{
DDRA = 0xFF;
i2c_InitSlave(); //initialize TWI module
i2c_listen(); //transmit start condition
PORTA = i2c_receive(1); //Receive only one byte
while(1);
}
Simulation:
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 53
Microcontroller Based System Design
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.
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.
The current rotational position of the servo motor output shaft is read by a potentiometer which
produces a voltage that is related to the absolute angle of the output shaft. The potentiometer
then feeds its value into the Error Signal Amplifier which compares the current position with the
required position from the PWM to voltage converter.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 54
Microcontroller Based System Design
The error signal amplifier is an operational amplifier with negative feedback. It will always try to
minimize the difference between the inverting and non-inverting inputs by driving its output in
the correct direction. The output of the error amplifier is either a negative or positive voltage
representing the difference between its inputs. Large error signal will produce higher output
voltages from error signal amplifier.
The error amplifier output is used to drive the motor. If it is positive the motor will turn in one
direction, otherwise in other direction. This allows the error amplifier to reduce the difference
between its inputs (thus closing the negative feedback loop) and so make the servo go to the
commanded position.
A typical value of the pulse width is somewhere in the range of 1.0 to 2.0ms. For a standard
servo, a pulse width between 1.0ms to 2.0ms makes the servo to turn between 0o to 180o.
However, these values could vary depending on the brand and make of the motor. A servo
motor has three wires; two for supply voltages (Vcc and Ground) and third wire is used to supply
the control PWM pulses.
Following figures show the different angle of rotation for the PWM of different duty cycles. Note
that for 1ms duty cycle PWM, servo does not rotate and the maximum rotation i.e. 180 o is
achieved with the PWM having duty cycle of 10% (2ms).
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 55
Microcontroller Based System Design
#include <avr/io.h>
#include <util/delay.h>
/*
CALCULATION:
We will use mode 14 (as per datasheet of ATmega16) to generate variable top PWM
with ICR1. We need to calculate the top value for 50Hz PWM Freq
Formula:
Freq PWM = Freq cpu /N(1+Top) so
Top = (Freq CPU / (Freq PWM x N))-1
where N is prescaler
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);
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 56
Microcontroller Based System Design
Simulation:
References:
M.A. Mazidi at. Al., “The AVR Microcontroller and Embedded Systems: Using Assembly
and C” ISBN-13: 978-0-13-800331-9, 2011
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad Page 57