Atmel AVR Workshop

Muhammad Aqeel Arshad 12-Jan-12

Electrical Engineering Department School of Science and Technology

This workshop is intended for students and hobbyists both. It is assumed that you know C language along with basic knowledge of digital circuits and knowledge of Microprocessor systems is a plus.


AVR-Microcontroller Workshop


An Embedded System is any electronic system that uses a computer chip, but that is not a general-purpose workstation, desktop or laptop computer. Such systems use microcontrollers (MCUs) or microprocessors (MPUs), or they may use custom-designed chips. The embedded systems market uses the lion's share of all the electronic components in the world. Embedded systems are employed in automobiles, planes, trains, space vehicles, machine tools, cameras, consumer electronics, office appliances, network appliances, video games, cellphones, PDAs, GPS navigation as well as robots and toys. Low-cost consumer products can use microcontroller chips that cost less than a few hundred Rupees. In Engineering Institutes theory about Embedded Systems is taught in courses like Microprocessor and Microcontroller Based Systems, Digital System Design, Computer Architecture and Organization but students pay little attention to the practical implementation of Embedded Systems. So they face a lot of difficulty doing their Final Year Projects, which mostly are built using microcontrollers. This workshop is intended for students and hobbyists both. It is assumed that you know C language along with basic knowledge of digital circuits and knowledge of Microprocessor systems is a plus. You will also learn the “language of datasheets” The PCB is built to make a starter board using Proteus software. Its files are provided in zip, you can edit them to make your own PCB. Atmega 16 microcontroller is easily available in local market and is also low cost. Most of the time you will different register names , don’t get afraid from that just open up the data sheet of the MCU and you can get detailed understanding of that register along with functionality of each bit. Join and Remember “Google is Your Friend”. Happy Programming  Muhamamd Aqeel Arshad

5 . Low-power AVR® 8-bit Microcontroller • Advanced RISC Architecture – 131 Powerful Instructions – Most Single-clock Cycle Execution – 32 x 8 General Purpose Working Registers • High Endurance Non-volatile Memory segments – 16K Bytes of In-System Self-programmable Flash program memory – 512 Bytes EEPROM – 1K Byte Internal SRAM • JTAG (IEEE std. and 25°C for ATmega16L – Active: 1.35 mA. 1149. 40 pin DIP package • Operating Voltages – 4.1 Compliant) Interface • Peripheral Features – Two 8-bit Timer/Counters with Separate Pre-scalers and Compare Modes – One 16-bit Timer/Counter with Separate Prescaler.UMT AVR-Microcontroller Workshop SST Back Ground Information Overview of the Microcontroller • High-performance. Idle Mode: 0. Power-down Mode: < 1 μA .5V for ATmega16 • Power Consumption @ 1 MHz. 10-bit ADC – Byte-oriented Two-wire Serial Interface – Programmable Serial USART – Master/Slave SPI Serial Interface – Programmable Watchdog Timer with Separate On-chip Oscillator – On-chip Analog Comparator • Special Microcontroller Features – Power-on Reset and Programmable Brown-out Detection – Internal Calibrated RC Oscillator • I/O and Packages – 32 Programmable I/O Lines.5. and Capture Mode – Real Time Counter with Separate Oscillator – Four PWM Channels – 8-channel.1 mA. Compare Mode. 3V.

Pxn is configured as an input pin. the pull-up resistor is activated. PORTxn has to be written logic zero or the pin has to be configured as an output pin. namely.b 1. The port pins are tri-stated when a reset condition becomes active. If programmed as input and the PORTxn is written logic one. I/O Ports I/O Ports are the most basic interface to the Microcontroller. There are 4 ports in ATMEGA16. PORTxn. If DDxn is written logic one. Pxn is configured as an output pin. . PORTA. To switch the pull-up resistor off.pololu. even if no clocks are running. Each port pin consists of three register bits: DDxn1.UMT AVR-Microcontroller Workshop SST Introduction to AVR Studio http://www. The PINx register is primarily used when the port is programmed as input. If programmed as output. The port pins are grouped using 8 bit ports. PORTC and PORTD. The PINxn register is a read only register that reflects the current logical value on the port pin. The DDxn bit in the DDRx Register selects the direction of this pin. and PINxn. PORTB. If DDxn is written logic zero. The PORTxn bit sets the logical value of the port

The Reset Value of the DDRx register is such that all port pins are programmed as inputs. After this a logic LOW on the pin will produce a Low Voltage Level and glow the LED and a logic HI on the pin turns LED off. In order to instruct the Microcontroller to produce voltage level on its pin. Port B is chosen to drive LEDs. The direction setting is to be done on the first time only as during the life cycle of the program the direction of the pin will remain as output. This is done through DDRx Register. The schematic of the example is given below.UMT AVR-Microcontroller Workshop SST Example 1 LEDs: Although connecting an LED to AVR Microcontroller is the easiest thing to do it may be a good start to connecting things to microcontroller. so we will exclusively program them as outputs. The Current capability of AVR Microcontroller is strong enough to drive an LED. the direction of the port pin is to be programmed as output. . A limiting resistor is however added to control the Light intensity.

Main block . .UMT AVR-Microcontroller Workshop SST ` Programming: Structure of code . 2.Go back to turn on LED Step. . On the start page goto “new project” or click “File” then “New” and then on “Project”.Turn on the LEDs by Writing 1s at the PORTB Register. AVR Studio 5: 1.Initialize the PORTB C as OUTPUT using DDRB Register. . Open AVR studio 5.Turn Off by Writing 0 at the PORTB Register.Delay to make us See the LED Glow. .Delay . .

4. Write down the code in the C file “LED_BLINKY. And in the name below write “LED_blinky” and Select the location where you want to save the project and press OK.C”.UMT AVR-Microcontroller Workshop SST 3. . 6. Now select “C Executable Project”. Select the device by writing “ATMEGA16” in the upper right box and press OK. 5.

10. } } //delay of 1000ms = 1sec for 1Mhz Clock of MCU //delay of 1000ms = 1sec for 1Mhz Clock of MCU 8. 9. Connect your Dev-board to USB Port and make sure you have installed the drivers of it USBTINY programmer. Select the hex file by clicking on the File Icon and select \Release\LED_Blinky. _delay_ms(1000). #include <avr/io. Remember to change “DEBUG” option to “Release”. 12. You can also check your design by simulating this example code in Proteus software. Press “F-7” or go-to “Build” and press “build Solution” to Generate the hex file.exe” and select “Atmega16” in device.h> // for delay purpose int main(void) { DDRB = 0xFF. _delay_ms(1000).hex . 11. PORTB = 0XFF.UMT AVR-Microcontroller Workshop SST 7. // while(1) { // main function make Bit 0 as output // infinite loop PORTB = 0X00. Open “Sina Prog. Select “USBtiny” as programmer.h> //contains all the register names and other related stuff #include <util/delay.

What change do you see? Exercise 2 Push Buttons: . Try adding line “#define F_CPU 4000000UL” before “#inlude<util/delay. 16. Click on the Flash program and wait for few sec to program the MCU.UMT AVR-Microcontroller Workshop SST 13.h>” line. 15. 14. Now you see a Blinking LED at 1Hz rate.

Set pin 2 and 3 of Portc as input (by default all pins are set to input). Enable internal pull-up at pin 2 and 3. To read the status of input.UMT AVR-Microcontroller Workshop SST Push button gives a way to give input. . Can you make 6 LED turn On and OFF by a Switch. // // main function Make all pins of Portb as output 1111_1111 DDRA = 0X00. - Check your code by burning it on ATmega 16 and make appropriate connections. Bit_is_clear(PINA. And to set any Pin as input write zero in specific DDRx Pin register. ///delay 100 mille sec. Remember PINx Reg contain the status on the Port.h> //contains all the register names and other related stuff #define F_CPU 8000000UL #include <util/delay. Check if Value of bit 1 in PINC Reg is 0 than turn on the LED.1) function tell us if the value of “pin 1” is 0 or not. _delay_ms(100). } } } // infinite loop // to check if sw4 on pinA register //PORTA = PORTA+1.3)) { PORTB++. Or make a digital DICE. In the below example two push buttons are connected to control one LED. Go back to check bit 1. all pins pulled up. If you press 1 push button LED turn on other turn off the LED. PINx register is used. while (bit_is_clear(PINA. // PORTA is as Input 0000_0000 PORTA = 0XFF. AVR Studio 5 Code: #include <avr/io. // enable internal pull on PORTA . while(1) { PORTB=PINA. Else Check if Value of bit 2 in PINC Reg is 0 than turn off the LED. Programming: Set pin 1 of Portc as output.h> // for delay purpose int main(void) { DDRB=0XFF.

thanks to the API (Functions used to easily access the modules) we provide. LCD Modules can present textual information to user.UMT AVR-Microcontroller Workshop SST Exercise 3 . allowing simple and fast reading/writing of data to and from the LCD.100" apart. the interface is a parallel bus. This waveform will write an ASCII Byte out to the LCD's screen. The ASCII code to be displayed is eight bits long and is sent to the LCD either four or eight bits at a time. Hello World on LCD When you start working with LCD modules you will start feeling the real power of MCU and your imaginations will be touching sky you will wonder how many exciting powerful gadgets you can create and that’s so very easily. The most popular one can display 2 lines of 16 characters. If four bit . They come in various types.14 Description Ground Vcc Contrast Voltage "R/S" _Instruction/Register Select "R/W" _Read/Write LCD Registers "E" Clock Data I/O Pins As you would probably guess from this description. These can be easily interfaced to MCU's. LCD interfacing is just fun! The most common connector used for the 44780 based LCDs is 14 pins in a row. The pins are wired as: Pins 1 2 3 4 5 6 7 . with pin centers 0. It’s like a cheap “monitor” that you can hook in all of your gadgets.

These files contain all the function to display at LCD. To wire a microcontroller to an LCD in four bit mode. Four bit mode requires a minimum of six bits.RW and EN are connected to PD4 . deciding how to send the data to the LCD is most critical decision to be made for an LCD interface application. Sending parallel data as either four or eight bits are the two primary modes of operation. two "nybbles" of data (Sent high four bits and then low four bits with an "E" Clock pulse with each nybble) are sent to make up a full eight bit transfer.UMT AVR-Microcontroller Workshop SST mode is used. If the Bit is set. then the byte at the current LCD "Cursor" Position can be read or written. The "R/S" bit is used to select whether data or an instruction is being transferred between the microcontroller and the LCD. just the top four bits (DB4-7) are written to. The different instructions available for use with the 44780 are shown in the table below: R/S R/W D7 D6 D5 D4 D3 D2 D1 D0 Instruction/Description 4 5 14 13 12 11 10 9 8 7 Pins 0 0 0 0 0 0 0 0 0 1 Clear Display 0 0 0 0 0 0 0 0 1 * Return Cursor and LCD to Home Position 0 0 0 0 0 0 0 1 ID S Set Cursor Move Direction 0 0 0 0 0 0 1 D C B Enable Display/Cursor 0 0 0 0 0 1 SC RL * * Move Cursor/Shift Display 0 0 0 0 1 DL N F * * Set Interface Length 0 0 0 1 A A A A A A Move Cursor into CGRAM 0 0 1 A A A A A A A Move Cursor to Display 0 1 BF * * * * * * * Poll the "Busy Flag" 1 0 D D D D D D D D Write a Character to the Display at the Current Cursor Position 1 1 D D D D D D D D Read the Character on the Display at the Current Cursor Position Thanks to already provided libraries.c. either an instruction is being sent to the LCD or the execution status of the last instruction is read back (whether or not it has completed). - Create a new project named “LCD” . PD5 and PD6 respectively. Eight bit mode is best used when speed is required in an application and at least ten I/O pins are available. The "E" Clock is used to initiate the data transfer within the LCD. The data port is connected at PORTC while RS . we will not write the above instructions instead we will include already available library. When the Bit is reset. In this project we will include two files mylcd. While there are secondary considerations and modes.h and mylcd.

UMT AVR-Microcontroller Workshop SST - Goto “Add”.h” in your main program LCD.c. “Existing Item..c .h and mylcd.” then add the both files mylcd. Also #include “mylcd..

If you look at the pin details you will find that ATMega 16 has one Serial port also called USART (Universal Synchronous Asynchronous Receiver Transmitter). Refer to datasheet of Atmega16. one is Interrupt based (Buffered) while other is polling based (nonBuffered).UMT AVR-Microcontroller Workshop SST AVR Studio Code: #include <avr/io. Hello World on Serial Port. lcd_string("::UMT AVR SST::"). Initialization: . while(1) { // //TODO:: Please write your application code } } Exercise 4.h" #include <util/delay. _delay_ms(100). first you need to initialize serial port as TX/RX Pins are multiplexed with PD0 and PD1 Pins. RX (Receive) pin is at 14 while TX (Transmitter) is at pin 15. Before you can send or receive any data.1).h> #define F_CPU 1000000UL #include "my_lcd.h> int main(void) { lcd_init(). To get a better understanding about serial communication . lcd_string("Hello World"). lcd_gotoxy(0. Two types of methods are used.

just search them in data sheet and you will the answer.UMT AVR-Microcontroller Workshop SST - FOCS is System Oscillator frequency. USART TRANSMIT DATA: . To know about these registers. Here our Baud rate is 9600pbs while data is 8 bits wide with 2 stop bits.

UMT USART RECEIVE DATA: AVR-Microcontroller Workshop SST Circuit Diagram: No external connection is needed as all the hardware is already connected on the PCB. AVR Studio 5 Code. UART_Receive function is called which checks the current port state and return SUCCES if a byte has been received or failure if the receive register is empty. To get a byte from USART. After initialization the system continuously wait for a byte to be received from UART and then displays its Value. It takes the data bit size. The initialization consists of setting up Timers and Port Registers. Serial port is initialized through 'InitUART'. The InitUART function is a very comprehensive function for UART Initialization as it takes care of different speed modes of controller. current clock frequency etc. Set avr Internal clock to “Int. 8Mhz” from SinaProg . and decide for a best possible baud rate generator register value. parity and stop bit values through parameters and sets the USART Registers accordingly.

/* Get and return received data from buffer */ return UDR.// (unsigned char)(baud>>8).// (unsigned char)baud.UMT AVR-Microcontroller Workshop SST #include <stdint.h> #include <util\delay. /* Enable receiver and transmitter */ UCSRB = (1<<RXEN)|(1<<TXEN). /* Set frame format: 8data. sends the data */ UDR = data.h> void USART_Init( unsigned int baud ) { /* Set baud rate */ UBRRH =0x00. /* Put data into buffer.h> #include <avr/io. } unsigned char USART_Receive( void ) { /* Wait for data to be received */ while ( !(UCSRA & (1<<RXC)) ). } . 1stop bit */ UCSRC = (1<<UCSZ1)|(1<<UCSZ0). } void USART_Transmit( unsigned char data ) { /* Wait for empty transmit buffer */ while ( !( UCSRA & (1<<UDRE)) ). UBRRL =baud.

} } Write the code for transmitting a whole string “Hello world” And simulate it on Proteus using Mhz crtytal settings. voltage. a sensor senses any physical parameter and converts into an equivalent analog electrical signal.UMT AVR-Microcontroller Workshop SST void USART_TX_STR (char str[]) { char i=0. we must process the data that we have received. it will start increasing gradually to 450°C. During its lightup. //9600 bps @ 8 Mhz while(1) { USART_Transmit('C'). the temperature never approaches directly to 800°C. Now. But analog signal processing is quite inefficient in terms of accuracy. This is an analog data. This digital signal is then fed to the Microcontroller (MCU) and is processed accordingly. pressure. the temperature inside a boiler is around 800°C. speed and desired output. while(str[i]!=0) USART_Transit } int main(void) { USART_Init(51). Signal Acquisition Process: In general. 500°C and thus reaches 800°C over a period of time.   . The ADC is connected to an 8-channel Analog Multiplexer which allows 8 single-ended voltage inputs constructed from the pins of Port A. their variation is always analog in nature. Whether it be temperature. this analog signal is converted into a digital signal using an Analog to Digital Converter (ADC). etc.  In the Real World. Most real world data is analog. Analogue to Digital Conversion (ADC): The ATmega16 features a 10-bit successive approximation ADC. For example. If the ambient temperature is 400°C. Exercise 5. Hence. For efficient and ease of signal processing. the signal (or data) acquisition process has 3 steps. we convert them to digital form using an Analog to Digital Converter (ADC). The single-ended voltage inputs refer to 0V (GND).

the major question is… which frequency to select? Out of the 50kHz-200kHz range of frequencies. We can straightaway use the inbuilt ADC of the MCU.UMT AVR-Microcontroller Workshop SST Interfacing Sensors: In general. 8. 16. So. a 0V input will give an ADC output of 0. The 0-5V range is divided into 2^10 = 1024 steps. if your application is not sophisticated and doesn’t require much accuracy. the ADC operates within a frequency range of 50kHz to 200kHz. you could go for higher frequencies. any analog value in between 0 and 5V is converted into its equivalent ADC value as shown above. For F_CPU = 16MHz. In ATMEGA16/32. ADC Prescaler: The ADC of the AVR converts analog signal into digital signal at some regular interval. 64. and 128. But the CPU clock frequency is much higher (in the order of MHz). For simple circuits. Now. This interval is determined by the clock frequency. Thus. There are some predefined division factors – 2. PORTA contains the ADC pins. 32. F_ADC = 16M/64 = 250kHz.5V input will give an ADC output of around 512. lesser the accuracy and vice-versa. a prescaler of 64 implies F_ADC = F_CPU/64. Greater the frequency. 4. But even this won’t be required if we use a MCU. So to achieve it. but a MCU is a digital one. . sensors provide with analog output. In this case. In general. Suppose we use a 5V reference. the answer lies in your need. The prescaler acts as this division factor. 5V input will give an ADC output of 1023. Hence we need to use ADC. which one do we need? Well. comparator op-amps can be used. For example. This is the basic concept of ADC. It produces desired frequency from the external higher frequency. frequency division must take place. whereas a 2. There is a trade-off between frequency and accuracy.

In any case. ADMUX Register The bits that are highlighted are of interest to us. we will discuss all the bits one by one.  Bits 7:6 – REFS1:0 – Reference Selection Bits – These bits are used to choose the reference voltage.UMT AVR-Microcontroller Workshop SST ADC Registers: We will discuss the registers one by one. Reference Voltage Selection . The following combinations are used. ADMUX – ADC Multiplexer Selection Register The ADMUX register is as follows.

Normally it takes 13 ADC clock pulses for this operation. Bits 4:0 – MUX4:0 – Analog Channel and Gain Selection Bits – There are 8 ADC channels (PA0…PA7). choose the last option for internal Vref. it consists of 2^5 = 32 different conditions as follows. For this. Let’s choose the second option for Vcc = 5V. AVCC and GND. For this we have a three pins AREF. Apart from this case. Unless this is enabled. or you may choose to leave it unconnected. This 1 is written as long as the conversion is in progress. PORTA will behave as GPIO pins. choose the first option. Which one do we choose? Choose any one! It doesn’t matter.e.  .UMT ADC Voltage Reference Pins AVR-Microcontroller Workshop SST The ADC needs a reference voltage to work upon. If you want to use the VCC (+5V). In any case. Bit 6 – ADSC – ADC Start Conversion – Write this to ’1′ before starting any conversion. ADC operations cannot take place across PORTA i.  ADCSRA – ADC Control and Status Register A The ADCSRA register is as follows. it enables the ADC feature. all the bits are set to zero.  Bit 7 – ADEN – ADC Enable – As the name says. But when you call it for the first time. We can supply our own reference voltage across AREF and GND. choose the second option. we are concerned only with the first 8 conditions. Initially. We will discuss about this a bit later. it takes 25 as it performs the initialization together with it. How to choose? You can choose it by setting these bits. you can either connect a capacitor across AREF pin and ground it to prevent from noise. we will discuss all the bits one by one. ADCSRA Register The bits that are highlighted are of interest to us.  Bit 5 – ADLAR – ADC Left Adjust Result – Make it ’1′ to Left Adjust the ADC Result. However. after which it returns to zero. Since there are 5 bits. Or else.

This is used in the case of interrupt-driven ADC. this is used to check whether the conversion is complete or not. we choose a prescaler of 128. ADCSRA = (1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0). Bits 2:0 – ADPS2:0 – ADC Prescaler Select Bits – The prescaler (division factor between XTAL frequency and the ADC clock frequency) is determined by selecting the proper combination from the following. Thus. it requires 10 bits to store the result. Thus. F_ADC = 16M/128 = 125kHz.    ADC Prescaler Selections Assuming XTAL frequency of 16MHz and the frequency range of 50kHz-200kHz. // prescaler = 128 ADCL and ADCH – ADC Data Registers The result of the ADC conversion is stored here. Bit 4 – ADIF – ADC Interrupt Flag – Whenever a conversion is finished and the registers are updated. Hence one single 8 bit register is not sufficient. the ADC interrupt is enabled. ADC is triggered automatically at every rising edge of clock pulse. this bit is set to ’1′ automatically. we initialize ADCSRA as follows. The two can be called together as ADC. Bit 3 – ADIE – ADC Interrupt Enable – When this bit is set to ’1′. Since the ADC has a resolution of 10 bits. . View the SFIOR register for more details.UMT  AVR-Microcontroller Workshop SST Bit 5 – ADATE – ADC Auto Trigger Enable – Setting it to ’1′ enables auto-triggering of ADC. Thus. We need two registers – ADCL and ADCH (ADC Low byte and ADC High byte) as follows.

Theses sensors differ in the range of temperature they work. Bimetals (Thermocouple) or radiation based (pyrometeric sensors). .5°C accuracy. price and signal conditioning required. Using LM35 : National Semiconductor has developed a chip that has the signal conditioning circuitry and the temperature sensing element on a small TO92 package. Composites (PTC Thermistor). Metals (PT100).UMT AVR-Microcontroller Workshop ADC Data Registers (ADLAR = 0) SST ADC Data Registers (ADLAR = 1) You can very well see the the effect of ADLAR bit (in ADMUX register). void adc_init() { // AREF = AVcc ADMUX = (1<<REFS0). Usually they are based on Semiconductors (NTC Thermistor). ADC Initialization The following code segment initializes the ADC. Upon setting ADLAR = 1. the conversion result is left adjusted. The chip gives quite accurate temperature reading for 0-100°C with an accuracy of 0. // ADC Enable and prescaler of 128 // 16000000/128 = 125000 ADCSRA = (1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0). A 10 bit ADC is sufficient to digitize the output produced by LM34 with 0.5°C. } Temperature Sensor A temperature sensor is probably the most primitive sensor built.

h" // initialize adc void adc_init() { // AREF = AVcc ADMUX = (1<<REFS0). ground on pin2 and connect using a jumper wire to ADC0 or pin40.h> #define F_CPU 8000000UL #include <util/delay. .h> #include "my_lcd. // ADC Enable and prescaler of 128 // 8000000/128 = 62. } // read adc value uint16_t adc_read(uint8_t ch) { // // // // select the corresponding channel 0~7 ANDing with '7' will always keep the value of 'ch' between 0 and 7 AND operation with 7 ch &= 0b00000111.UMT AVR-Microcontroller Workshop SST Circuit Diagram Connect LM35 on the bread board with 5volt on pin1 .5 Khz ADCSRA = (1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0). AVR studio code: #include <avr/io.

lcd_gotoxy(0. The fast PWM differs from the other PWM option by its single-slope operation. //LM35 gives out 10mv/C lcd_gotoxy(9. However. lcd_integer(adc_result0.UMT ADMUX = (ADMUX & 0xF8)|ch. } int main() { uint16_t adc_result0.3). AVR-Microcontroller Workshop // clears the bottom 3 bits before ORing // start single conversion // write '1' to ADSC SST ADCSRA |= (1<<ADSC). run loop continuously & (1<<ADSC)). the pulse width increases as the instantaneous modulating-signal level increases (positive modulation). // display the labels on LCD lcd_string("ADC on AVR"). this can be reversed so that higher signal levels cause the pulse width to decrease (negative modulation). // read adc value at PA0 adc_result0=((adc_result0*500+512)/1023). All Timers of ATMEGA 16 has capability to produce PWM signals. lcd_string(" TEMP= C'").1). The width (duration) of each individual pulse varies according to the modulating analog signal. _delay_ms(50). // // // while(ADCSRA wait for conversion to complete ADSC becomes '0' again till then. Normally.1). return (ADC). The counter counts from BOTTOM . namely Fast PWM Mode and Phase Correct PWM Mode. while(1) { adc_result0 = adc_read(0). The Timers of ATMEGA 16 has different PWM Modes. _delay_ms(500). // initialize adc and lcd adc_init(). PWM on AVR: Pulse-Width Modulation (PWM) also called pulse-duration modulation (PDM) is a method of converting analog information using digital communication techniques. In PWM a train of pulses is produced. } } Exercise 7. lcd_init(). _delay_ms(50). These modes are discussed below Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode provides a high frequency PWM waveform generation option.

In non-inverting Compare Output mode. the output is set on compare match and cleared at BOTTOM. . the operation is inverted. The TCNTn value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. In phase correct PWM mode the counter is incremented until the counter value matches MAX. the counter is incremented until the counter value matches the MAX value. The timing diagram for the fast PWM mode is shown in Figure VII-1. and therefore reduces total system cost. The phase correct PWM mode is based on a dual slope operation. Due to the single. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNTn slopes represent compare matches between OCRn and TCNTn. The counter is then cleared at the following timer clock cycle. the Output Compare (OCn) is cleared on the compare match between TCNTn and OCRn while up counting. In fast PWM mode. The PWM resolution for the phase correct PWM mode is fixed to eight bits. the Output Compare (OCn) is cleared on the compare match between TCNTn and OCRn. Phase Correct PWM Mode: The phase correct PWM mode (WGMn1:0 = 1) provides a high resolution phase correct PWM waveform generation option. due to the symmetric feature of the dual-slope PWM modes. When the counter reaches MAX. the operating frequency of the fast PWM mode can be twice as high as the phase correct PWM mode that uses dual slope operation. The dualslope operation has lower maximum operation frequency than single slope operation. capacitors). This high frequency makes the fast PWM mode well suited for power regulation.UMT AVR-Microcontroller Workshop SST to MAX then restarts from BOTTOM. and set at BOTTOM. The timing diagram for the phase correct PWM mode is shown on Figure VII-2. it changes the count direction. In non-inverting Compare Output mode. In inverting Compare Output mode. However. and DAC applications. rectification.slope operation. The counter counts repeatedly from BOTTOM to MAX and then from MAX to BOTTOM. The small horizontal line marks on the TCNT0 slopes represent compare matches between OCRn and TCNTn. and set on the compare match while down counting. In inverting Output Compare mode. The TCNTn value is in the timing diagram shown as a histogram for illustrating the single-slope operation. these modes are preferred for motor control applications. The TCNTn value will be equal to MAX for one timer clock cycle. The diagram includes non-inverted and inverted PWM outputs. High frequency allows physically small sized external components (coils.

c * * Created: 26-Dec-11 12:29:32 AM * Author: aqeel */ #include <avr/io.UMT AVR-Microcontroller Workshop SST PWM Circuit: AVR STUDIO 5 CODE: /* * PWM.h" void pwm_start(unsigned char PULSE_WIDTH) .h> #include"my_lcd.h> #include<avr/io.h> #define F_CPU 8000000UL #include<util/delay.h> #include<stdio.

PA2)) { if(width==0) //stops underflow to 255 width=1. //stops overflow to zero = = = = 0. WRITE CODE FOR SERVO MOTOR. } return 0. 1. PORTA|=(1<<PA1)|(1<<PA2). DISPLAY VALUES OF LM 35 TEMP ON BAR LED. Non-Inverted PWM //Start PWM width++. width--.PA1)) { if(width==255) width=254. 2. DDRA &=~((1<<PA1)|(1<<PA2)). pwm_start(width). PORTB=width.UMT { OCR1AL OCR1AH TCCR1A TCCR1B = = = = PULSE_WIDTH. RUN BAR LED IN CHASSER MODE. 0. // width increases _delay_ms(100). 1. 4. //Load Pulse width //8-bit. Non-Inverted PWM //Start PWM } int main () { unsigned char width=0. OCR1AL OCR1AH TCCR1A TCCR1B while(1) { if(bit_is_clear(PINA. _delay_ms(100). . if(width==255) width=254. 1. AVR-Microcontroller Workshop SST //Load Pulse width //8-bit. 0x81. 0x81. 0. SEND ADC VALUES AT SERIAL PORT. DDRC = 0XFF. } THINGS TO DO. } if(bit_is_clear(PINA. 3. } //OCR1AL=width.

so we can make it better next time. _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ What difficulties you faced regarding this event? _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ What things you like about this event? _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ .UMT AVR-Microcontroller Workshop SST Feed Back Form  Please write down your comments about this event.

Sign up to vote on this title
UsefulNot useful