Electronic – How to generate a pwm signal that varies atleast 20times between 0-5V range using Atmeaga32 avr mcu

avrmicrocontrollerpwm

I'm doing a Photovoltaic(PV) Data Logger project in this, a power
MOSFET(IRFZ34N) can be used as load.So i want to vary the gate voltage
using a PWM signal(0-5v range) of MCU & i need at least 2o varying points.
so i am confusing at writing a 'C' code to generate PWM signal.
like 1. what should be the time period of PWM?
2. how can i vary pwm duty cycle in different steps? and etc..

And please help me, if anything else that i have to do to make my
project success full.
I would be very thank full, if some body help me with answer.

Best Answer

You can do this in software and keep track of all the required timing yourself, but most microcontrollers have hardware that can generate PWM autonomous after you initialize it. The basic things are a timer/counter and an Output Compare Register (OCR):

enter image description here

The counter continuously increments, represented by the slope, and is compared with the OCR. The PWM output goes low when the counter exceeds the OCR, and goes high again when it resets. The 5 % resolution you need (20 steps) is not a problem; a 16 bit timer can generate PWM with a better than 0.002 % resolution, and even an 8 bit timer can do 0.4 %.

All you have to do is program a new value in the OCR. The lower the value, the smaller the pulse width. The following animation is from this site:

enter image description here

Further reading
Using the AVR’s High-speed PWM, an Atmel application note.
ATMega32 datasheet describes on page 69 ff. how to use Timer0 for PWM operation.