Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * program to change brightness of an LED
- * demonstration of PWM
- */
- #include <avr/io.h>
- #include <util/delay.h>
- // #define F_CPU 16000000UL
- // initialize PWM
- void pwm_init() {
- // initialize timer0 in PWM mode
- TCCR0A |= (1<<WGM00)|(1<<WGM01)|(1<<WGM02)|(1<<COM0A1)|(1<<COM0A0)|(1<<CS00);
- TCCR0B |= (1<<WGM00)|(1<<WGM01)|(1<<WGM02)|(1<<COM0A1)|(1<<COM0A0)|(1<<CS00);
- // make sure to make OC0 pin (pin PB2 for atmega168) as output pin
- DDRB |= (1 << PB1);
- PORTB |= (1 << PB1);
- DDRB |= (1 << PB2);
- }
- int main() {
- unsigned int brightness;
- // initialize timer0 in PWM mode
- pwm_init();
- // run forever
- while(1) {
- // increasing brightness
- for (brightness = 0; brightness < 30; ++brightness) {
- // set the brightness as duty cycle
- // delay so as to make the user "see" the change in brightness
- OCR0A = brightness;
- PORTB |= (1 << PB2);
- _delay_ms( 30 - brightness );
- PORTB ^= ~(1 << PB2);
- _delay_ms( brightness );
- }
- // decreasing brightness
- for (brightness = 30; brightness > 0; --brightness) {
- // set the brightness as duty cycle
- // delay so as to make the user "see" the change in brightness
- OCR0A = brightness;
- PORTB |= (1 << PB2);
- _delay_ms( brightness );
- PORTB ^= ~(1 << PB2);
- _delay_ms( 30 - brightness );
- }
- // repeat this forever
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement