AVR PWM configuration

492 views Asked by At

I know this is silly but I got really confused.

I want to make a PWM pulse with 3 modes on Atmega16: 1- 1Khz with Duty cycle 100% 2- 4Khz with Duty cycle 100% 3- 1Khz with Duty cycle 50%

I was away from AVR for almost 2 years and I forgot everything, so I just need the calculations of Timer 1 in a simple way. any thing I have read makes me more confused. Is there something that could help me? I'm using Codevision AVR.

2

There are 2 answers

0
Ahmad Afkande On BEST ANSWER

I did this, but I got exams so it got too long to post it. I set the Fcpu to 4MHz

and here is the code:

void set1KhzDC100()
{
// Timer/Counter 1 initialization
// Clock source: System Clock
// Clock value: 500.000 kHz
// Mode: Fast PWM top=0x01FF
// OC1A output: Non-Inv.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
// Timer1 Overflow Interrupt: Off
// Input Capture Interrupt: Off
// Compare A Match Interrupt: Off
// Compare B Match Interrupt: Off
TCCR1A=0x82;
TCCR1B=0x0A;
TCNT1H=0;
TCNT1L=0;
ICR1H=0x00;
ICR1L=0x00;
OCR1A=511;
}

void Set4KhzDC100()
{
// Timer/Counter 1 initialization
// Clock source: System Clock
// Clock value: 4000.000 kHz
// Mode: Fast PWM top=0x03FF
// OC1A output: Non-Inv.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
// Timer1 Overflow Interrupt: Off
// Input Capture Interrupt: Off
// Compare A Match Interrupt: Off
// Compare B Match Interrupt: Off
TCCR1A=0x83;
TCCR1B=0x09;
TCNT1H=0x00;
TCNT1L=0x00;
ICR1H=0x00;
ICR1L=0x00;
OCR1A=1023;
OCR1BH=0x00;
OCR1BL=0x00;
}

void Set1KhzDC50()
{
// Timer/Counter 1 initialization
// Clock source: System Clock
// Clock value: 500.000 kHz
// Mode: Fast PWM top=0x01FF
// OC1A output: Non-Inv.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
// Timer1 Overflow Interrupt: Off
// Input Capture Interrupt: Off
// Compare A Match Interrupt: Off
// Compare B Match Interrupt: Off
TCCR1A=0x82;
TCCR1B=0x0A;
TCNT1H=0;
TCNT1L=0;
ICR1H=0x00;
ICR1L=0x00;
OCR1A=255;
}
0
UncleO On

1- 1Khz with Duty cycle 100%

2- 4Khz with Duty cycle 100%

are the same thing. There is no actual PWM at all. The output is high all the time and frequency doesn't matter.

3- 1Khz with Duty cycle 50%

is actually PWM. There are a few types to choose from, but if the duty cycle is going to be exactly 50%, then there are easy ways to achieve this with a toggle. From the manual,

A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting OC1A to toggle its logical level on each compare match (COM1A1:0 = 1). This applies only if OCR1A is used to define the TOP value (WGM13:0 = 15).

That is, set the COM1A1 and COM1A0 bits of TCCR1A to be 01, and set all the WGM bits of TCCR1A and TCCR1B to be 1. Choose OCR1A and the CSx prescalar bits of TCCR1B so that OCR1A is reached every 0.5 ms.