1-Microcontroller Based System Design - Complete
1-Microcontroller Based System Design - Complete
LIST OF EXPERIMENTS
S. #
1. 2. 3. 4. 5. 6. 7. 8. 9.
Title
I/O Ports Programming & LED Interfacing Seven Segment Display Interfacing Timer and Counter Programming Interrupt Programming Serial Port Interfacing and Programming LCD Interfacing ADC Programming PWM Programming SPI Programming
Page #
2 5 8 14 19 25 29 34 39 44 51
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 1
We will be using the Atmel Studio 4.19 having built-in GCC compiler to write the C code for ATmega16 AVR Microcontroller. Proteus 7.6 for simulation and Genius G540 Universal Programmer for burning the code to ATmega16.
Theory:
Following three registers are associated to each I/O port of ATmega16: DDRx Data Direction Register to set the port input or output PORTx To write data on I/O pin if port configured as output using DDRx PINx To read data from I/O pins if port is configured as input using DDRx DDxn 0 0 1 1 PORTxn 0 1 0 1 I/O Input Input Output Output Comment Tri-state (Hi-Z) Pxn will source current if externally pulled down Output Low (Sink) Output High (Source)
For writing a high byte on Port A, we need to do the following: DDRA = 0xFF; PORTA = 0xFF; //0xFF = 1111 1111 (make Port A as output) //Send 1 to all pins of Port A
For reading a byte from Port A, we need to do the following: unsigned char x; //define a variable to store the value of PINA DDRA =0x00; //0x00 = 0000 0000 (make PORTA as input) x = PINA; //Read value to Port A and store on variable x I/O Ports - Bit Manipulation using Macros: Ports of the AVR ATmega16 cannot be accessed bitwise. So if we want to perform any function on a single bit, following macros can be used for bit manipulation:
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 2
Macros definition: #define #define #define #define #define #define BitGet(p, m) BitSet(p, m) BitClear(p, m) BitFlip(p, m) BitWrite(c,p,m) Bit(x) ((p) & (m)) ((p) |= (m)) ((p) &= ~(m)) ((p) ^= (m)) (c ? BitSet(p,m) : BitClear(p,m)) (0x01 << (x))
To clear bit number 6 of PORTA with a bit mask: Code: BitClear(PORTA, 0x40); // PORTA = x0xx xxxx (x are dont cares)
To check bit number 3 of PORTA: Code: if(BitGet(PORTA, Bit(3))) //Check if Bit 3 of PORTA == 1
if (BitGet (PORTA, Bit (4))) // If Bit 4 of PORTA == 1 then set Bit 0 of PORTB BitSet ((PORTB, Bit (0)); // Else clear Bit 0 of PORTB else BitClear (PORTB, Bit (0));
To copy the status of single bit of a register to single bit of another register: Code:
BitWrite (BitGet (PORTA, BIT (4)), PORTB, Bit (0)); //PORTB, Bit0 = PORTA, Bit4
while(1) //Forever Loop { _delay_ms (1000); //Delay of 1 Second PORTA = ~PORTA; //Toggle state of port A }
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 3
Simulation:
Home Task:
If Bit 0 of PORTB is high, LEDs connected at PORTA will glow from LSB to MSB. If Bit 0 of PORTB is low, LEDs connected at PORTA will light from LSB to MSB.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 4
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 5
void Display(unsigned char n) { unsigned char units, tens; { tens = n/10; // units = n%10; // for(x = 0; x<1100; x++) // { PORTB = 0xFE; // PORTA = Seven_Segment[units]; // _delay_us(500);
Separate tens from a two digit number Separate units from a two digit number Generate delay of about 1 second Select one display to show units value Display units
PORTB = 0xFD; // Select second display to show tens value PORTA = Seven_Segment[tens]; // Display tens _delay_us(500);
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 6
Simulation:
Home Task:
Extend the above circuit to four 7-segment displays. Value of least significant 7 segment display is incremented after every 125 milliseconds (approx). Attach three push buttons with three MSBs of PortB. When Switch 1 (PortB.7) is pressed, counting stops and current value is retained on the 7-segment displays constantly. Now by pressing Switch 2 (PortB.6), value displayed on 7-segment displays is incremented and by pressing switch 3 (PortB.5), value on 7-segment displays is decremented. Now again by pressing Switch 1, counting is started from the new/changed value on 7-segment displays. Note: Define, declare and use the functions, UpCount(), DownCount(), SetCount() in your code.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 7
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.
Page 8
7 FOC0
W 0
6 WGM00
RW 0
5 COM01
RW 0
4 COM00
RW 0
3 WGM01
RW 0
2 CS02
RW 0
1 CS01
RW 0
0 CS00
RW 0
FOC0
Force Output Compare: FOC0 bit is only active when the WGM00:1 bits specifies a non-PWM mode. This bit is always read as zero. When this bit is set, and a compare with WGM01 0 1 0 1 Timer Mode 0 Selector Bits (Four modes available) Normal Mode CTC (Clear Timer on Compare Match) Mode PWM, Phase Correct Mode Fast PWM Compare Output Mode: These bits control waveform generation, if CTC mode is selected through WGM00-01 bits then: Normal mode operation Toggle OC0 (PB3, Pin 4) on compare match Clear OC0 on compare match Set OC0 on compare match Timer 0 Clock Source Selector No clock source (Timer/Counter stopped) clk (No Prescaling) clk / 8 clk / 64 clk / 256 clk / 1024 External clock on T0 (PB0) pin. Clock on falling edge External clock on T0 (PB0) pin. Clock on rising edge
WGM00 0 0 1 1
COM01 : COM00 0 0 1 1 0 1 0 1
CS02:00 D2 D1 D0 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1
7 OCF2
W 0
6 TOV2
RW 0
5 ICF1
RW 0
4 OCF1A
RW 0
3 OCF1B
RW 0
2 TOV1
RW 0
1 OCF0
RW 0
0 TOV0
RW 0
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 9
D0 D1 D2 D3 D4 D5 D6 D7
Timer 0 overflow flag bit (0 = Timer0 did not overflow) Timer 0 output compare flag (0 = compare match did not occur) Timer 1 overflow flag bit Timer 1 output compare B match flag Timer 1 output compare A match flag Input capture flag Timer 2 overflow flag Timer 2 output compare flag
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
void TimerDelay(void); //Function prototype declaration void main(void) { DDRA = 0xFF; BitSet(PORTA, Bit(0));
while(1) { BitFlip(PORTA, Bit(0)); //Toggle PA0 TimerDelay(); //Generates delay of about 100ms }
/* delay calculation For a clock generation of 5Hz (200ms), timer should be overflowed twice, so: Timer overflow @ = 200ms / 2 = 100ms (0.1s high, 0.1s low) Crystal Clock = 1MHz Prescaler used = 1024 Timer clock = 1MHz / 1024 = 976.5625 Hz Timer Period = 1/976.5625 = 1024us Timer Value = 0.1s / 1024us = 97.65625 = 98 (approx) */ void TimerDelay(void) { TCNT0 = 0x9F; TCCR0 = 0x05; while(!BitGet(TIFR, Bit(0))); TCCR0 = 0x00; BitSet(TIFR, Bit(0)); }
// (256+1)-98 = 159 = 0x9F //Timer0 ON, clk/1024 prescaler, Normal Mode // Wait for timer0 overflow & TOV0 flag is raised //Stop Timer //Clear TOV0
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 11
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> //Start of main program void main(void) { PORTB = 0x02; //Set a pull-up on PB2 (T1)
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 12
TCCR1A = 0x00; //Enable Counter Mode no falling adge at PB1 TCCR1B = 0x06; while(1) { PORTC = TCNT1H; //Send higher byte of counter to PortC PORTA = TCNT1L; //Send lower byte of counter to PortA }
Simulation:
Home Task:
Generate a Square wave of frequencies according to last two digits of your registration numbers. Even registration numbers will generate Hertz and odd will generate kHz. For Example: 1625/BSEE/FET/F11 will generate square wave of 25 kHz.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 13
Introduction:
There are two methods by which a microcontroller can serve a device 1- Interrupt: In interrupt method, a device sends an interrupt signal to microcontroller. Upon reception of interrupt, microcontroller stops its working and serves the device. Program executed after receiving an interrupt is called Interrupt Service Routine (ISR). 2- Polling: In polling, microcontroller continuously monitors the status of device, if the status is met, microcontroller serves the device. In polling method, microcontroller can only check single device at a time.
Address
$000 $002 $004 $006 $008 $00A $00C $00E $010 $012 $014 $016 $018 $01A $01C $01E $020 $022 $024 $026 $028
Source
Reset INT0 INT1 TIMER2 COMP TIMER2 OVF TIMER1 CAPT TIMER1 COMPA TIMER1 COMPB TIMER1 OVF TIMER0 OVF SPI, STC USART, RXC USART, UDRE USART, TXC ADC EE_RDY ANA_COMP TWI INT2 TIMER0 COMP SPM_RDY
Interrupt Definition
External Pin, Power-on Reset, Brown-out Reset, Watchdog Reset, and JTAG AVR Reset External Interrupt Request 0 External Interrupt Request 1 Timer/Counter2 Compare Match Timer/Counter2 Overflow Timer/Counter1 Capture Event Timer/Counter1 Compare Match A Timer/Counter1 Compare Match B TIMER1 OVF Timer/Counter1 Overflow Timer/Counter0 Overflow Serial Transfer Complete Rx Complete USART Data Register Empty USART, Tx Complete ADC Conversion Complete EEPROM Ready Analog Comparator Two-wire Serial Interface External Interrupt Request 2 Timer/Counter0 Compare Match Store Program Memory Ready
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 14
Microcontroller Based System Design Above table shows the interrupt sources and their interrupt vectors for AVR ATmega16. Memory locations from 0002 to 0028 locations are reserve for interrupt vectors. Each interrupt has 2 words (4 bytes) of memory space for its ISR. For example, 0012 to 0014 memory space is set aside for Timer0 overflow ISR. Usually ISR cannot fit into 4-bytes memory space. So a JMP instruction is kept at the vector address from where ISR jumps to another location where rest of the code of ISR can be written. At the end of each ISR, RETI (Return from Interrupt) instruction is placed which gives the control back to the location from where it was interrupted.
When interrupt is executed, Bit D7 of SREG is cleared by the microcontroller to avoid the occurrence of another interrupt. Moreover, if Timer0 overflow interrupt is enabled, TOV0 (Timer0 Overflow flag) is automatically cleared when microcontroller jumps to the Timer0 overflow interrupt vector table.
TIMER INTERRUPTS:
Timer Interrupt Mask Register (TIMSK) holds the different interrupt enable bits related to timers.
Bit # Bit Name TOIE0 OCIE0 TOIE1 OCIE1B OCIE1A TICIE1 T0IE2 OCIE2 7 OCIE2 6 T0IE2 5 TICIE1 4 OCIE1A 3 OCIE1B 2 TOIE1 1 OCIE0 0 TOIE0
Timer0 overflow interrupt enable Timer0 output compare match interrupt enable Timer1 overflow interrupt enable Timer1 output compare B match interrupt enable Timer1 output compare A match interrupt enable Timer1 input compare interrupt enable Timer2 overflow interrupt enable Timer2 output compare match interrupt enable
These bits, along with D7 of SREG, when set, enable the corresponding interrupt. Upon execution of interrupt, each flag is cleared by AVR itself and D7 of SREG is also disabled to avoid further interrupt when ISR of an interrupt is being executed.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 15
External hardware interrupt request 0 enable External hardware interrupt request 1 enable External hardware interrupt request 2 enable
GICR (General Interrupt Control Register) INT0 and INT1 can be programmed to trigger on low level, rising edge, falling edge or both edges through MCUCR (MCU Control Register). Whereas, INT2 can only be programmed to trigger on falling or rising edge through MCUCSR (MCU Control and Status Register). If an interrupt is programmed for edge trigger mode, the pulse must be 1 instruction cycle to ensure that the transition is seen by microcontroller. If an interrupt is programmed for level trigger, the pin must be held low for at least 5 machine cycles to cause an interrupt.
Bit # Bit Name ISC01 0 0 1 1 ISC11 0 0 1 1 7 SE ISC00 0 1 0 1 ISC10 0 1 0 1 6 SM2 Description Low level of INT0 generates an interrupt request Any logic change on INT0 generates an interrupt request Falling edge of INT0 generates an interrupt request Rising edge of INT0 generates an interrupt request Description Low level of INT1 generates an interrupt request Any logic change on INT1 generates an interrupt request Falling edge of INT1 generates an interrupt request Rising edge of INT1 generates an interrupt request 5 SM1 4 SM0 3 ISC11 2 ISC10 1 ISC01 0 ISC00
Description The falling edge of INT2 generates an interrupt request The rising edge of INT2 generates an interrupt request
MCUCSR (MCU Control and Status Register) GIFR (General Interrupt Flag Register) has external interrupt flags. When an external interrupt is occurs, corresponding flag of that external interrupt is raised. When microcontroller jumps of the interrupt vector table, flag is automatically cleared or we can clear the flag by writing high on it.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 16
7 INTF1
6 INTF0
5 INTF2
4 -
3 -
2 -
1 -
0 -
When an external interrupt occurs, its corresponding flag bit in GIFR is set. When AVR jumps to its ISR, this flag is cleared by AVR. For level triggering, pin must be hold for at least 5 instruction cycles to be recognized.
int main(void) { DDRD = 0xFF; //Make PortD output BitSet(DDRA, Bit(0)); //Make PA0 output BitClear(DDRB, Bit(2)); //Make PB2 as input for INT2 BitSet(PORTB, Bit(2)); //Internally pull-up PB2 BitSet(TIMSK, Bit(1)); //Enable OC0IE bit to enable Timer0 Compare Mode interrupt BitSet(GICR, Bit(5)); //Enable INT2 bit to enable External Interrupt 2 BitClear(MCUCSR, Bit(6)); //Configure Falling edge triggered INT2 interrupt sei(); //Enable Global Interrupt OCR0 = 98; TCCR0 = 0x0D; } while(1); //98 calculated in the last lab for 0.1 seconds time //0000 1101, CTC Mode, Crystal Clock, 1024 prescaler //Stay here forever
//Interrupt Service Routines (ISRs) of Timer0 CTC Mode & External Interrupt INT2 ISR (TIMER0_COMP_vect) //ISR for Timer0 CTC Output Compare { BitFlip(PORTA, Bit(0)); //Toggle PB0 } ISR (INT2_vect) { PORTD++; } //ISR for External Interrupt INT2 //At every falling edge of INT2, increment PortD
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 17
Simulation:
Home Task:
Repeat the home task of Lab-3. At the same time, interface a push button with external interrupt0. When this button is pressed (external interrupt 0 is invoked), square wave generation should be stopped. When this button is pressed again, square wave generation should start again.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 18
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.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Microcontroller Based System Design UCSRA: UCSRB: UCSRC: UBRR: USART Control Status Register A: For controlling serial communication in AVR USART Control Status Register B: For controlling serial communication in AVR USART Control Status Register C: For controlling serial communication in AVR USART Baud Rate Register: Value written in this register determines the baud rate
or = 16(
16( + 1) ) 1
Where X is the value loaded in the UBRR for a specific desired baud rate. Above calculation will be true for default setting upon reset.
RXC
USART Receive Complete: When a complete byte is received, this flag is set. Cleared when buffer is empty. This flag is also used to generate receive complete interrupt. USART Transmit Complete: When a complete byte is transmitted, this flag is set. Cleared when buffer is empty. This flag is also used to generate transmit complete interrupt. Automatically cleared when interrupt is executed. USART Data Register Empty: This flag is set when transmit data buffer is empty and it is ready to receive new data. If this flag is cleared, data should not be written into UDR. This flag is also used to generate data register empty interrupt. Framing Error: This bit is set, if there is error in the frame of next received byte. Frame error is generated when the first stop bit of next character in the received buffer is zero. Data Overrun: A data overrun occurs when the received data buffer and received shift register are full, and a new start bit is detected. Set flag enables data overrun. Parity Error: This bit is set if parity checking is enabled (UPM1 = 1) and the next character in the receive buffer has a parity error. Double the USART Transmission Speed: Setting this bit will double the baud rate for asynchronous communication. Multiprocessor Communication Mode: This enables the multi-processor communication mode. The MPCM is not discussed in this lab Page 20
TXC
UDRE
FE
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
FE, PE and DOR are valid until UDR is read. Set these to zero for transmission For crystal frequency of 1MHz and 8MHz, the most commonly used baud rates for asynchronous operation can be generated by using the UBRR settings shown in the following table:
Fosc = 1MHz Baud Rate (bps) 2400 4800 9600 14400 25 12 6 3 U2X = 0 UBRR Error 0.2% 0.2% -7.0% 8.5% U2X = 1 UBRR 51 25 12 8 Error 0.2% 0.2% 0.2% -3.5% U2X = 0 UBRR 207 103 51 34 Error 0.2% 0.2% 0.2% -0.8% Fosc = 8MHz U2X = 1 UBRR 416 207 103 68 Error -0.1% 0.2% 0.2% 0.6%
RXCIE
USART Receive Complete Interrupt Enable: Setting this bit enables the receive complete interrupt USART Transmit Complete Interrupt Enable: Setting this bit enables the transmit complete interrupt USART Data Register Empty Interrupt Enable: Setting this bit enables the data register empty interrupt USART Receive Enable: Setting this bit enables USART receiver USART Transmit Enable: Setting this bit enables USART transmitter USART Character Size: See bit USCZ0 and USCZ1 in UCSRC Receive data bit 8: When using serial frames with nine data bits, the ninth received bit of every frame is placed in this RXB8. Transmit data bit 8: When using serial frames with nine data bits, the ninth transmitted bit of every frame is placed in this TXB8.
TXCIE
UDRIE
TXB8
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 21
URSEL
UMSEL
Register Select: Setting this bit enables to change the contents of UCSRC register else, UBRRH is selected Mode Select: Setting this bit selects Asynchronous mode, else synchronous mode Parity Mode: For parity generation and check 00 Disables 01 Reserved 10 Even Parity 11 Odd Parity Stop Bit Select: Setting this bit will add 2 stop bits in frame else 1 stop bit Character Size: Combined with Bit2 (UCSZ2) selects the different data bits in a frame UCSZ2 : 0 000 001 010 011 111 Character Size 5 6 7 8 9
UPM1:0
USBS UCSZ1:0
UCPOL
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 22
//PortA as output //0x35 = 53 ~ 53.0833 = (1000000/(16*1200))-1 //enable //enable //enable //enable Receive Complete Interrupt Transmit Complete Interrupt Receiving Transmission
//enables 8 bit character size //enables 8 bit character size //enables 8 bit character size //writes on UCSRC register if this bit is 1 //when clear, UBRRH value will be updated //enable global interrupt //stay here forever
//ISR for Receive interrupt ISR (USART_RXC_vect) { x = UDR; //Store the received character into x x++; //increment received character UDR = x; //Transmit the incremented character } //ISR for Transmit interrupt ISR (USART_TXC_vect) //This interrupt will trigger when transmission is complete { PORTA++; //increment PortA to show that transmit interrupt is executed }
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 23
Simulation:
Home Task:
Through serial port, transmit your name from the serial port to AVR and AVR should return back first four digits of your registration number. Use crystal oscillator of 1MHz. Set the baud rate to the nearest available range as per the following formula: (Goupr No.) x (1800) = Baud Rate
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 24
Introduction:
This lab demonstrated that an LCD can be interfaced in 4-bit mode to an ATmega16 AVR microcontroller. LCD can also be used in 8-bit mode but the advantage of using it in 4-bit mode is that we can save the I/O ports of a microcontroller. In 4-bit mode, we need to send the character after splitting it into higher and lower nibbles (4-bits for data only).
PIN 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
SYMBOL Vss Vcc Vdd RS R/W E DB0 DB1 DB2 DB3 DB4 DB5 DB6 DB7 BLA BLK
DESCRIPTION Power supply (GND) Power supply (+5V) Contrast Settings (0~2V) 0 = Select command reg. 1 = Select data reg. of LCD 0 = Write to LCD 1 = Read from LCD The Enable (E) line allows access to the display through R/W and RS lines Data bit line 0 (LSB) Data bit line 1 Data bit line 2 Data bit line 3 Data bit line 4 Data bit line 5 Data bit line 6 Data bit line 7 (MSB) Backlight Anode (+) Backlight Anode (+) Supply connections and pin diagram of 16x2 LCD For 4-bit Mode, only these pins are used as data bits
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 25
Following table shows some useful command list which is generally required to interface and program the microcontroller with LCD.
Line No. 1 2
Character Positions 00 01 02 03 08 09 10 11 00 01 02 03 08 09 10 11 04 05 06 07 12 13 14 15 04 05 06 07 12 13 14 15
DDRAM Address 80 81 82 83 88 89 8A 8B C0 C1 C2 C3 C8 C9 CA CB 84 85 86 87 8C 8D 8E 8F C4 C5 C6 C7 CC CD CE CF
1. 2. 3. 4. 5.
Set R/W bit to low Set RS bit to logic 0 or 1 (command or character) Set data to data lines (if it is writing) Set E to high and then low for some time Finally write the data from data lines (if it is reading)
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 26
#include<avr/io.h> #include<util/delay.h> //Macros Definition #define BitSet(p,m) #define BitClr(p, m) #define BitFlip(p,m) #define Bit(x) void void void void void
((p) |= (m)) ((p) &= ~(m)) ((p) ^= (m)) (0x01 << (x))
unsigned int main(void) { unsigned char data0[]="DEE"; unsigned char data1[]="FET, IIUI"; unsigned int i=0; DDRA=0xFF; LCD_init(); cmd_4b(0x87); while(data0[i]!='\0') { data_4b(data0[i]); _delay_ms(50); i++; } cmd_4b(0xC4); i=0; while(data1[i]!='\0') { data_4b(data1[i]); _delay_ms(50); i++; } while(1);
//Initialize LCD //Cursor at Line 1, Position 7 //continue loop until null is arrived //send all characters for 4-bit data conversion //to access next character of array //Cursor at Line 2, Position 4 //continue loop until null is arrived //send all characters for 4-bit data conversion //to access next character of array
// Initialize LCD //to initialize LCD in 4-bit mode. //to initialize LCD in 2 lines, 5x7 dots and 4bit mode //Display is ON, cursor OFF
void cmd_4b(unsigned char Cmd) { char Cmd1; Cmd1 = Cmd & 0xF0; //mask lower nibble because PA4-PA7 pins are used LCDcmd(Cmd1); // send to LCD Cmd = Cmd << 4; //shift left 4 bits
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 27
void data_4b(unsigned char data_value) { char data_value1; data_value1 = data_value & 0xF0; LCDdata(data_value1); data_value1 = data_value << 4; LCDdata(data_value1); } void LCDcmd(unsigned char cmdout) { PORTA = cmdout; BitClr(PORTA, Bit(0)); //Clear RS BitClr(PORTA, Bit(1)); //Clear RW BitSet(PORTA, Bit(2)); //Set Enable _delay_us(200); BitClr(PORTA, Bit(2)); //Clear Enable } void LCDdata(unsigned char dataout) { PORTA = dataout; BitSet(PORTA, Bit(0)); //Set RS BitClr(PORTA, Bit(1)); //Clear RW BitSet(PORTA, Bit(2)); //Set Enable _delay_us(200); BitClr(PORTA, Bit(2)); //Clear Enable }
Simulation:
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 28
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.
ADCSRA : ADC control and status register SFIOR : Three MSBs of this register are used to select the auto trigger source of ADC
1024
where Vin is the voltage on the selected input channel, Vref the selected voltage reference and ADC is the 10-bit converted digital decimal value. Similarly, differential input result can be found from following formula: = ( ) 512
where Vpos and Vneg are the two differential input channels and the Gain can be selected as 1x, 10x and 200x from ADMUX register.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 29
7 REFS1
6 REFS0
5 ADLAR
4 MUX4
3 MUX3
2 MUX2
1 MUX1
0 MUX0
Reference selection bits 0 0 AREF, Internal Vref turned off 0 1 AVCC with external capacitor at AREF pin 1 0 Reserved 1 1 Internal 2.56V Voltage Reference with external capacitor at AREF pin ADC Left Adjusted Result. When this bit is set, ADCL contains only two LSBs of the result at position D7 and D6. Remaining bits are not used Analog channel and gain selection bits. See following table for details
ADLAR
MUX4 : 0
Single Ended I/P ADC0 ADC1 ADC2 ADC3 ADC4 ADC5 ADC6 ADC7
Gain
NA
NA
ADC0 ADC1 ADC0 ADC1 ADC2 ADC3 ADC2 ADC3 ADC0 ADC1 ADC2 ADC3 ADC4 ADC5 ADC6 ADC7 ADC0 ADC1 ADC2 ADC3 ADC4 ADC5
ADC0 ADC0 ADC0 ADC0 ADC2 ADC2 ADC2 ADC2 ADC1 ADC1 ADC1 ADC1 ADC1 ADC1 ADC1 ADC1 ADC2 ADC2 ADC2 ADC2 ADC2 ADC1 NA
1.22V(VBG) 0V (GND)
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 30
7 ADEN
6 ADSC
5 ADATE
4 ADIF
3 ADIE
2 ADPS2
1 ADPS1
0 ADPS0
ADC Enable ADC Start conversion. In Single Conversion mode, write this bit to one to start each conversion. ADC Auto Trigger Enable. When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a con-version on a positive edge of the selected trigger signal. The trigger source is selected by setting the ADC Trigger Select bits, ADTS in SFIOR. ADC Interrupt Flag. This bit is set when an ADC conversion completes and the Data Registers are updated. ADIF is cleared by hardware when executing the corresponding interrupt handling vector otherwise it is cleared by writing a logical one to the flag When this bit is written to one and the I-bit in SREG is set, the ADC Conversion Complete Inter-rupt is activated. ADC Prescaler Select Bits. These bits determine the division factor between the XTAL frequency and the input clock to the ADC. See following table
ADIF
ADIE ADPS2:0
ADPS1
0 0 1 1 0 0 1 1
ADPS0
0 1 0 1 0 1 0 1
Division Factor
Reserved 2 4 8 16 32 64 128
7 ADTS2
6 ADTS1
5 ADTS0
4 -
3 ACME
2 PUD
1 PSR2
0 PSR10
ADC Auto Trigger Source Free Running Mode Analog Comparator External Interrupt Request 0 Timer / Counter 0 compare match Timer / Counter 0 overflow Timer / Counter 1 compare match B Timer / Counter 1 overflow Timer / Counter 1 capture event
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 31
Page 32
int main(void) { DDRA = 0x00; DDRD = 0xFF; DDRB = 0xFF; InitADC(); sei(); while(1); }
//PortA as input for ADC input //PortD as output for lower byte of Digital value //PortB as output for higher byte of Digital value //Enable global interrupt
void InitADC(void) { BitSet(ADMUX, Bit(7)); BitSet(ADMUX, Bit(6)); BitClr(ADMUX, Bit(5)); BitClr(ADMUX, Bit(4)); BitClr(ADMUX, Bit(3)); BitClr(ADMUX, Bit(2)); BitClr(ADMUX, Bit(1)); BitClr(ADMUX, Bit(0)); //ADMUX = 0xC0; BitSet(ADCSRA, BitClr(ADCSRA, BitSet(ADCSRA, BitSet(ADCSRA, BitSet(ADCSRA, BitSet(ADCSRA, Bit(7)); Bit(5)); Bit(3)); Bit(2)); Bit(1)); Bit(0));
//Internal 2.56V selected as Vref //Internal 2.56V selected as Vref //Right adjusted result //Single ended (GND as common ground) //non-differential input on ADC0 channel (PA0, Pin No. 40) // // // //Same settings as given above //Enable ADC //Disable Auto Trigger //Enable ADC Interrupt //Prescaler = Fosc/128 //Prescaler = Fosc/128 //Prescaler = Fosc/128
BitSet(ADCSRA, Bit(6)); //Start Conversion //ADCSRA = 0xCF ; //Same settings as described above
Simulation:
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 33
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.
WGM01:00 bits of TCCR0 register are used to select the different modes of timer.
Bit # Bit Name
Read/Write Initial Value
255 256
6
7 FOC0
W 0
5 COM01
RW 0
4 COM00
RW 0
3 WGM01
RW 0
2 CS02
RW 0
1 CS01
RW 0
0 CS00
RW 0
WGM00
RW 0
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 34
Force Output Compare: FOC0 bit is only active when the WGM00:1 bits specifies a non-PWM mode. Timer Mode 0 Selector Bits (Four modes available) Normal Mode CTC (Clear Timer on Compare Match) Mode PWM, Phase Correct Mode Fast PWM Compare Output Mode: used to select the following operation if Fast PWM is selected through WGM01:00: Disconnect, Normal port operation, OC0 disconnected Reserved Non-inverted, Clear OC0 on compare match, set OC0 at Top Inverted, Set OC0 on compare match, clearOC0 on Top Timer 0 Clock Source Selector No clock source (Timer/Counter stopped) clk (No Prescaling) clk / 8 clk / 64 clk / 256 clk / 1024 External clock on T0 (PB0) pin. Clock on falling edge External clock on T0 (PB0) pin. Clock on rising edge
COM01 : COM00 0 0 1 1 0 1 0 1
CS02:00 D2 D1 D0 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1
Page 35
Microcontroller Based System Design whether to set or clear the OC0 pin after compare match is occurred while counting upward. Similarly, while counting downward, on the compare match, OC0 pin can be programmed to set or clear. In non-inverted phase correct mode, OC0 pin is cleared when compare match occurs while TCNT0 is counting upward and set OC0 pin when compare match occurs while TCNT0 is counting downward. Reverse is the case from Inverted phase correct PWM. Both of these modes of Phase Correct PWM can be understood from the Fig 8.2.
Value to be loaded in OCR0 to generate the PWM of required duty cycle can be determined from the following formula: = = 0 100 255 Non-inverted Mode Phase Correct PWM
255 255
100
In TCCR0, Phase Correct PWM Mode can be selected by WGM01:00 = 01. For Phase Correct PWM Mode, COM01:00 bits of TCCR0 performs the following operation: COM01:00
0 0 1 1 0 1 1 1
Mode
Normal Reserved
Operation
Normal port operation, OC0 disconnected
Non-inverting Clear OC0 on up-counting compare, Set OC0 on down-counting compare Inverting Set OC0 on up-counting compare, Clear OC0 on down-counting compare
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 36
Microcontroller Based System Design As Timer2 is also 8-bit timer, therefore it works similar to Timer0. The differences are the register names, output pin and the prescaler of TCCRx register. For Timer0 and Timer2 the Top is fixed (0xFF). Timer1 is a 16-bit timer. Modes of Timer1 can be selected from TCCR1B TCCR1A registers. Details of PWM generation through Timer1 are beyond the scope of this lab. However, the basic principle is same as discussed earlier.
Bit # Bit Name
Read/Write Initial Value
7 ICNC1
RW 0
6 ICES1
RW 0
5 RW 0
4 WGM13
RW 0
3 WGM12
RW 0
2 CS12
RW 0
1 CS11
RW 0
0 CS10
RW 0
D7 D6 WGM01
WGM 11 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 10 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
Setting this bit enables the input noise canceller Setting this bit enables the input capture on falling edge Timer1 Modes (WGM11:10 are in TCCR1A)
Timer/Counter Mode of Operation Normal PWM, Phase Correct, 8 bit PWM, Phase Correct, 9 bit PWM, Phase Correct, 10 bit CTC Fast PWM, 8 bit Fast PWM, 9 bit Fast PWM, 10 bit PWM, Phase & Frequency Correct PWM, Phase & Frequency Correct PWM, Phase Correct PWM, Phase Correct CTC Reserved Fast PWM Fast PWM Top 0xFFFF 0x00FF 0x01FF 0x03FF OCR1A 0x00FF 0x01FF 0x03FF ICR1 OCR1A ICR1 OCR1A ICR1 ICR1 OCR1A Top Type Fixed Fixed Fixed Fixed Variable Fixed Fixed Fixed Variable Variable Variable Variable Variable Variable Variable Update of OCR1x Immediate Top Top Top Immediate Top Top Top Bottom Bottom Top Top Immediate Top Top TOV Flag Set on Max Bottom Bottom Bottom Max Top Top Top Top Bottom Bottom Bottom Bottom Max Top Top
CS12:10 D2 D1 D0 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1
Timer 1 Clock Source Selector No clock source (Timer/Counter stopped) clk (No Prescaling) clk / 8 clk / 64 clk / 256 clk / 1024 External clock on T1 (PB1) pin. Clock on falling edge External clock on T1 (PB1) pin. Clock on rising edge
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 37
Simulation:
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 38
Introduction:
The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the AVR and peripheral devices or between several AVR devices. The ATmega16 SPI includes the following features: Full-duplex Synchronous Data Transfer Master or Slave Operation LSB First or MSB First Data Transfer Seven Programmable Bit Rates End of Transmission Interrupt Flag Write Collision Flag Protection Double Speed (CK/2) Master SPI Mode
Following figure shows the interconnection between two SPI devices. The system consists of communication by pulling low the SS pin of desired slave device. SCK is the clock signal which is generated by Master device. Data between both the devices is exchanged by SCK clock rate. Data is always shifted from Master to Slave on MOSI (Master Out, Slave In) and from Slave to Master on MISO (Master In, Slave Out) pin. Master will pull the SS pin high after transmission of data.
When device is configured as Master, SPI has no control on SS pin. This pin must be controlled by software. Before start of transmission from Mater to Slave, SS pin must be kept low. After shifting one byte, the SPI clock generator stops, setting the end of Transmission Flag (SPIF). If the SPI Interrupt Enable bit (SPIE) in the SPCR Register is set, an interrupt is requested. The Master may continue to shift the next byte by writing it into SPDR, or signal the end of packet by pulling high the Slave Select, SS line. The last incoming byte will be kept in the Buffer Register for later use. When configured as a Slave, the SPI interface will remain sleeping with MISO tri-stated as long as the SS pin is driven high. In this state, software may update the contents of the SPI Data
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 39
Microcontroller Based System Design Register, but the data will not be shifted out by incoming clock pulses on the SCK pin until the SS pin is driven low. As one byte has been completely shifted, the end of Transmission Flag, SPIF is set. If the SPI Interrupt Enable bit (SPIE) is set, an interrupt is requested. The Slave may continue to place new data to be sent into SPDR before reading the incoming data. The last incoming byte will be kept in the Buffer Register for later use. For Slave, minimum low and high period of the clock on SCK pin should be longer than 02 CPU clock cycles. Following three registers are related to SPI of ATmega16: SPSR (SPI Status Register) SPCR (SPI Control Register) SPDR (SPI Data Register)
7 SPIF 6 WCOL 5 4 3 2 1 0 SPI2X
SPI Interrupt Flag: When a serial transfer is complete, the SPIF Flag is set. An interrupt is generated if SPIE in SPCR is set and global interrupts are enabled. If SS is an input and is driven low when the SPI is in Master mode, this will also set the SPIF Flag. SPIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, the SPIF bit is cleared by first reading the SPI Status Register with SPIF set, then accessing the SPI Data Register (SPDR). Write Collision Flag: The WCOL bit is set if the SPI Data Register (SPDR) is written during a data transfer. The WCOL bit (and the SPIF bit) are cleared by first reading the SPI Status Register with WCOL set, and then accessing the SPI Data Register. Double SPI Speed: When this bit is written logic one the SPI speed (SCK Frequency) will be doubled when the SPI is in Master mode
WCOL
SPI2X
SPIE
SPI Interrupt Enable: This bit causes the SPI interrupt to be executed if SPIF bit in the SPSR Register is set and if the global interrupt enable bit in SREG is set. SPI Enable: When the SPE bit is written to one, the SPI is enabled. This bit must be set to enable any SPI operations. Data Order: When the DORD bit is written to one, the LSB of the data word is transmitted first. When the DORD bit is written to zero, the MSB of the data word is transmitted first. Master/Slave Select: This bit selects Master SPI mode when written to one and Slave SPI mode when written logic zero. If SS is configured as an input and is driven low while MSTR is set, MSTR will be cleared, and SPIF in SPSR will become set. The user will then have to set MSTR to re-enable SPI Master mode.
SPE DORD
MSTR
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 40
SPCR (SPI Control Register) There are four combinations of SCK phase and polarity with respect to serial data, which are determined by control bits CPOL and CPHA in SPCR register: SPI Mode 0 1 2 3 CPOL 0 0 1 1 CPHA 0 1 0 1 Operation Read on rising edge, Setup on falling edge Read on falling edge, Setup on rising edge Read on falling edge, Setup on rising edge Read on rising edge, Setup on falling edge
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 41
C Code for data transfer between two ATmega16 using SPI feature of AVR:
/* This program transmits a character from first ATmega16 microcontroller and receives the same on other microcontroller. SPI feature of ATmega16 is used to complete the task. */ ///////////////// CODE FOR MASTER///////////////// #include<avr/io.h> #include<util\delay.h> #define #define #define #define MOSI MISO SCK SS 5 6 7 4
/////////////// Macros Definition///////////////// #define Bit(x) (0x01 << (x)) #define BitGet1 (p, m) ((p) & (m)) #define BitSet(p, m) ((p) |= (m)) #define BitClr(p, m) ((p) &= ~(m)) void main(void) { unsigned char x=0; DDRB=(1<<SS)|(1<<SCK)|(1<<MOSI); DDRB=~(1<<MISO); BitSet(SPCR, Bit(6)); BitSet(SPCR, Bit(4)); BitSet(SPCR, Bit(0)); while(1) { BitClr(PORTB, Bit(SS)); SPDR=x; while(!(BitGet(SPSR, Bit(7)))); BitSet(PORTB, Bit(SS)); _delay_ms(500); x++; } //Make these pins as output //Make MISO as input //Enable SPI //Enable Mater //Select SCK Freq as Fos/16
//Enable Slave Select Pin //Load SPI Data Register for transmission //wait until SPI Interrupt Flag is raised //Disable Slave Select Pin
///////////////// CODE FOR SLAVE///////////////// #include<avr/io.h> #define MOSI 5 #define MISO 6 #define SCK 7 #define SS 4 /////////////// Macros Definition///////////////// #define Bit(x) (0x01 << (x)) #define BitGet(p, m) ((p) & (m)) #define BitSet(p, m) ((p) |= (m)) #define BitClr(p, m) ((p) &= ~(m)) void main(void) { Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 42
Simulation:
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 43
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 44
Page 45
Microcontroller Based System Design STOP conditions, while the receiver is responsible for acknowledging the reception. An Acknowledge (ACK) is signaled by the receiver pulling the SDA line low during the ninth SCL cycle. If the receiver leaves the SDA line high, a NACK is signaled. When the receiver has received the last byte, or for some reason cannot receive any more bytes, it should inform the transmitter by sending a NACK after the final byte.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 46
TWI Registers:
As shown in the above block diagram, TWI module of AVR has following registers: TWDR TWAR TWBR TWSR TWCR TWI Data register TWI Slave address register TWI Bit Rate register TWI Status register TWI Control register
In receive mode, TWDR will have received byte and in transmit mode, TWDR will have byte to be transmitted. TWAR contains the 7-bit slave address to which TWI will respond when working as slave. LSB (Bit 0) of TWAR is TWGCE. Setting this bit enables the recognition of general call. TWBR selects the division factor to control the SCL clock frequency while working in Master mode. SCL frequency can be calculated from following formula: =
Where, TWBR holds the 8-bit value for a required SCL frequency. TWPS are two bits for prescaler in TWSR register.
Bit # Bit Name 7 TWS7 6 TWS6 5 TWS5 4 TWS4 3 TWS3 2 1 TWPS1 0 TWPS0
16 + 2(
)4
TWS7:3
TWS: TWI Status: These five bits show the status of TWI control and bus. For more details, see datasheet TWI Prescaler Bits: 00 1 01 4 10 16 11 64
TWPS1:0
This bit is set by hardware when the TWI has finished its current job and expects application software response. If the I-bit in SREG and TWIE in TWCR are set, the MCU will jump to the TWI Interrupt Vector. While the TWINT Flag is set, the SCL low period is stretched. The TWINT Flag must be cleared by software by writing a logic one to it. Note that this flag is not automatically cleared by hardware when executing the interrupt routine. Also note that clearing this flag starts the operation of the TWI, so all accesses to the TWI Address Register (TWAR), TWI Status Register (TWSR), and TWI Data Register (TWDR) must be complete before clearing this flag.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 47
TWEA
The TWEA bit controls the generation of the acknowledge pulse. If the TWEA bit is written to one, the ACK pulse is generated on the TWI bus if the following conditions are met: 1. The devices own Slave address has been received. 2. A general call has been received, while the TWGCE bit in the TWAR is set. 3. A data byte has been received in Master Receiver or Slave Receiver mode. By writing the TWEA bit to zero, the device can be virtually disconnected from the Two-wire Serial Bus temporarily. Address recognition can then be resumed by writing the TWEA bit to one again. The application writes the TWSTA bit to one when it desires to become a Master on the Two-wire Serial Bus. The TWI hardware checks if the bus is available, and generates a START condition on the bus if it is free. However, if the bus is not free, the TWI waits until a STOP condition is detected, and then generates a new START condition to claim the bus Master status. TWSTA must be cleared by software when the START condition has been transmitted. Writing the TWSTO bit to one in Master mode will generate a STOP condition on the Two-wire Serial Bus. When the STOP condition is executed on the bus, the TWSTO bit is cleared automatically. In Slave mode, setting the TWSTO bit can be used to recover from an error condition. This will not generate a STOP condition, but the TWI returns to a well-defined unaddressed Slave mode and releases the SCL and SDA lines to a high impedance state. The Write collusion bit is set when attempting to write to the TWI Data Register TWDR when TWINT is low. This flag is cleared by writing the TWDR Register when TWINT is high. The TWEN bit enables TWI operation and activates the TWI interface. When TWEN is written to one, the TWI takes control over the I/O pins connected to the SCL and SDA pins, enabling the slew-rate limiters and spike filters. If this bit is written to zero, the TWI is switched off and all TWI transmissions are terminated, regardless of any ongoing operation. When this bit is written to one, and the I-bit in SREG is set, the TWI interrupt request will be activated for as long as the TWINT Flag is high.
TWSTA
TWSTO
TWWC
TWEN
TWIE
C Code for data transfer between two ATmega16 using TWI feature of AVR:
/* This program transmits a character from Master ATmega16 microcontroller and receives the same on Slave microcontroller. TWI feature of ATmega16 is used to complete the task. */ ///////////////// CODE FOR MASTER///////////////// #include<avr/io.h> /////////////// Macros Definition///////////////// #define Bit(x) (0x01 << (x)) #define BitGet(p, m) ((p) & (m)) #define BitSet(p, m) ((p) |= (m)) #define BitClr(p, m) ((p) &= ~(m)) Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 48
//Use zero prescaler //for SCL Freq = 1kHz and Fosc = 1MHz //Enable TWEN, TWI Module
//Clear TWINT, TWI Interrupt Flag //Enable TWSTA, TWI Start Condition //Enable TWEN, TWI Module Enable //Stay till start condition transmitted
//Place date to be transmitted in TWI Data reg //Clear TWEN, TWI Interrupt Flag //Enable TWEN, TWI Module Enable //Stay till data transmitted
//Clear TWINT, TWI Interrupt Flag //Enable TWSTA, TWI Stop Condition //Enable TWEN, TWI Module Enable //Stay till stop condition transmitted
//initialize TWI module //transmit start condition //call the address of slave 0x55 //Transmit ASCII of character A //Transmit start condition
///////////////// CODE FOR SLAVE///////////////// #include<avr/io.h> /////////////// Macros Definition///////////////// #define Bit(x) (0x01 << (x)) #define BitGet(p, m) ((p) & (m)) #define BitSet(p, m) ((p) |= (m)) #define BitClr(p, m) ((p) &= ~(m)) void i2c_InitSlave(void) { TWCR = 0x04; TWAR = 0b01010101; BitSet(TWCR, Bit(7)); BitSet(TWCR, Bit(6)); BitSet(TWCR, Bit(2)); }
//Enable TWEN, TWI Module //Set Slave address //Clear TWINT, TWI Interrupt Flag //Enable TWEA, Send Acknowledge //Enable TWEN, TWI Module Enable
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 49
void i2c_listen(void) { while(!(BitGet(TWCR, Bit(7)))); //Stay till data transmitted } unsigned char i2c_receive(unsigned char ChkLast) { if(!ChkLast) //Place date to be transmitted in TWI Data reg { BitSet(TWCR, Bit(7)); //Clear TWINT, TWI Interrupt Flag BitSet(TWCR, Bit(6)); //Enable TWEA, Send Acknowledge BitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enable } else { BitSet(TWCR, Bit(7)); //Clear TWINT, TWI Interrupt Flag BitSet(TWCR, Bit(2)); //Enable TWEN, TWI Module Enable } while(!(BitGet(TWCR, Bit(7)))); //Stay till data byte received return (TWDR); } void main(void) { DDRA = 0xFF; i2c_InitSlave(); i2c_listen(); PORTA = i2c_receive(1); while(1); }
//initialize TWI module //transmit start condition //Receive only one byte
Simulation:
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 50
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.
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
A typical value of the pulse width is somewhere in the range of 1.0 to 2.0ms. For a standard servo, a pulse width between 1.0ms to 2.0ms makes the servo to turn between 0o to 180o. However, these values could vary depending on the brand and make of the motor. A servo motor has three wires; two for supply voltages (Vcc and Ground) and third wire is used to supply the control PWM pulses. Following figures show the different angle of rotation for the PWM of different duty cycles. Note that for 1ms duty cycle PWM, servo does not rotate and the maximum rotation i.e. 180o is achieved with the PWM having duty cycle of 10% (2ms).
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 52
Position of Servo Motor against different pulse widths 5% of 20ms = 1ms = 0 degree (min. rotation) 10% of 20ms = 2ms = 180 degrees (max. rotation) 5% Duty Cycle Calculation for non-inverting mode: Duty Cycle (%) = ((OCR1x + 1) / Top + 1) * 100 5 / 100 = (OCR1x + 1) / (2499 + 1) 0.05 * 2500 = OCR1x + 1 OCR1x = 124 10% Duty Cycle Calculation for non-inverting mode: Duty Cycle (%) = ((OCR1x + 1) / Top + 1) * 100 10 / 100 = (OCR1x + 1) / (2499 + 1) 0.1 * 2500 = OCR1x + 1 OCR1x = 249
*/
void main(void) { unsigned int x; //Configure Timer1 registers TCCR1A |= (1<<COM1A1)|(1<<WGM11); //Non-Inverted PWM TCCR1B |= (1<<WGM13)|(1<<WGM12)|(1<<CS11); //Prescaler=16 Mode 14(Fast PWM) ICR1 = 2499; //Freq PWM=50Hz, Time Period = 20ms DDRD = 0xFF; //PWM generation on PortD5 while(1) { x = 124; //1ms = 5% of 20ms pulse OCR1A = x; //0 degree rotation initially _delay_ms(1000); while(x <= 249) { OCR1A=x; _delay_ms(50); x++; } // continue till 2ms = 10% of 20ms Pulse
Prepared by: Engr. M. Muzammil, DEE, FET, International Islamic University, Islamabad
Page 53
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 54