Most AVRs contain PWM hardware, especially the newer ones, which typically have two or more PWM units built-in. A PWM signal is one in which the ratio between a pause and a signal is changing as seen in Figure 1.
I will not bother to explain the internal structure of a PWM unit within an AVR MCU. For the time being, let me just say that a PWM unit is a part of the Timer circuit. Most AVRs have at least 2 PWMs: one associated with Timer0 and one associated with Timer1. When selecting the microcontroller that we want to use for PWM generation, we have to set the resolution of the PWM that we would like to have: 8, 9 or 10 bits. 8-bit PWM means that our PWM signal is changing within 256 steps, while 512 or 1024 steps are achieved with 9 or 10 bits respectively. Not all AVRs offer more than 8-bit PWM resolution. For everyday use – say to drive an LED or a simple motor, 8-bit PWM is more than enough, while other applications require a higher resolution PWM signal. We will focus on 8-bit PWM.
Programming
Let us start our Bascom-AVR program. First, we have to configure a suitable Timer. If we require 8-bit PWM then we select an 8-bit timer. We can also select a 16-bit timer and configure it as an 8-bit PWM timer as you can see below:
Config Timer1 = Pwm , Pwm = 8 ,
Compare A Pwm = Clear Down , Prescale = 1
This configuration statement is valid for most AVRs. In this sample we used it with an ATmega16 microcontroller, but program PWM1.bas can also be used with other AVRs. Be aware that AVR timers have Compare outputs designated with the letters A, B and C. If we configure Compare A Pwm = Clear Down then we will be using Output Compare 1A (OC1A) as an output pin. In the case of the ATmega16 that corresponds to the PortD.5 pin. It’s nearly all done. All that is remaining is to load the PWM counter with the value of a byte variable, as follows:
COMPARE1A = N
If we now change the value of N from 0 to 255 and back to 0 while observing an LED connected to PortD.5, we will see that LED is slowly turning on and then slowly fading out. A simple and wonderful example of driving an LED with PWM!
When Bascom’s Config statement is used to configure a timer in PWM mode, it automatically takes care of setting the direction of the Output Compare pin to the Output mode. If you were to do the configuration yourself, using the AVRs timer registers directly, you would have to do this step yourself.
Something about PWM in Bascom-AVR
2012_AVR_UK_55
Continue reading
Shop area
|