Advertisement
doctorkarn

HW_LAB_4_1 (draft)

Sep 17th, 2014
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. /**
  2. * program to change brightness of an LED
  3. * demonstration of PWM
  4. */
  5.  
  6. ‪#‎include‬ <avr/io.h>
  7. #include <util/delay.h>
  8. // ‪#‎define‬ F_CPU 16000000UL
  9.  
  10. // initialize PWM
  11. void pwm_init() {
  12. // initialize timer0 in PWM mode
  13. TCCR0A |= (1<<WGM00)|(1<<WGM01)|(1<<WGM02)|(1<<COM0A1)|(1<<COM0A0)|(1<<CS00);
  14. TCCR0B |= (1<<WGM00)|(1<<WGM01)|(1<<WGM02)|(1<<COM0A1)|(1<<COM0A0)|(1<<CS00);
  15.  
  16. // make sure to make OC0 pin (pin PB2 for atmega168) as output pin
  17. DDRB |= (1 << PB1);
  18. PORTB |= (1 << PB1);
  19. DDRB |= (1 << PB2);
  20. }
  21.  
  22. int main() {
  23. unsigned int brightness;
  24.  
  25. // initialize timer0 in PWM mode
  26. pwm_init();
  27.  
  28. // run forever
  29. while(1) {
  30. // increasing brightness
  31. for (brightness = 0; brightness < 30; ++brightness) {
  32. // set the brightness as duty cycle
  33. // delay so as to make the user "see" the change in brightness
  34. OCR0A = brightness;
  35. PORTB |= (1 << PB2);
  36. _delay_ms( 30 - brightness );
  37. PORTB ^= ~(1 << PB2);
  38. _delay_ms( brightness );
  39. }
  40.  
  41. // decreasing brightness
  42. for (brightness = 30; brightness > 0; --brightness) {
  43. // set the brightness as duty cycle
  44. // delay so as to make the user "see" the change in brightness
  45. OCR0A = brightness;
  46. PORTB |= (1 << PB2);
  47. _delay_ms( brightness );
  48. PORTB ^= ~(1 << PB2);
  49. _delay_ms( 30 - brightness );
  50. }
  51.  
  52. // repeat this forever
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement