14
2016-Jan
AVR 초패스트 PWM
작성자: Blonix
IP ADRESS: *.148.87.98 조회 수: 1564
출처 : http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&p=614762#614762
주파수 최강자. 다만 하드웨어 pwm이 아니고 소프트웨어 pwm이라 정밀도는 좀 떨어짐.
사실 아주 특수한 케이스가 아니면 딱히 쓸 곳 없음. 진짜 엄청빠른 주파수가 필요한 특수한 경우가 아니라면..
What it shows is how to do PWM on an arbitrary pin by doing "soft PWM" but with timer interrupts. It works by starting a timer to have both overflow (PWM frequency) and compare (duty cycle) interrupts. In this case I wanted to vary a pulse width on PC0 using the fastest PWM frequency I could get (so timer 0 counting 256 with no prescaler) and OCR0 can be varied from 0x00 to 0xFF to vary the duty cycle:
// The following two ISRs are doing "poor man's PWM"
// but this allows it to be on a pin of my choice
ISR(TIMER0_COMP_vect) {
// clear the output pin on OCR0 match
PORTC &= ~(1<<PC0);
}
ISR(TIMER0_OVF_vect) {
// set the output pin at timer overflow
PORTC |= (1<<PC0);
}
int main(void) {
// going to use PORTC.0 to PWM the contrast voltage
DDRC = (1<<DDC0);
TIMSK |= ((1<<OCIE0) | (1<<TOIE0)); // use both interrupts
OCR0 = 10; // 10 out of 256 means very short on period (low voltage)
TCCR0 = (1<<CS00); // timer on - nice high PWM frequency
// Might later consider PWMing the backlight voltage too
// so it would also be adjustable ...
sei();
this is just a code "snippet" for GCC, not a complete program.
The application was actually to vary the pin 3 (contrast) voltage of an HD44780 LCD module. As the comments say it would be possible to vary the backlight voltage in a similar way.
The way this example works is that it runs an 8bit timer with no prescale so every 256 clock cycles it will overflow and cause an OVF interrupt. At this point the output is turned on. The counter then starts to count up 0, 1, 2, 3,... and I have set the OCR0 register to 10 so when it counts up to 10 and TCNT0==OCR0 it will trigger the COMP(are) interrupt. At this point I switch the output off. So in a complete period of 256 counts the output is on for 10 and off for 246. So the output is only "on" for about 4% of the time. As the output pin is switching between 0V and 5V then it'll be like a voltage that is just 4% of this will be produced by the output pin (after a bit of RC filtering). So it's 4% * 5V = 0.19V
In my example I don't vary OCR so the output voltage is always at this level. But say I now set OCR to 211 (out of 256) then the output signal will be on for 211 clocks and off for 256-211=45 clocks. Because of this the output will appear to be 211/256 * 5V = 4.12V (and so on).