backlight.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <avr/io.h>
  2. #include "backlight.h"
  3. #include "atomic.h"
  4. #define CHANNEL OCR1C
  5. void backlight_init_ports()
  6. {
  7. // Setup PB7 as output and output low.
  8. DDRB |= (1<<7);
  9. PORTB &= ~(1<<7);
  10. // Use full 16-bit resolution.
  11. ICR1 = 0xFFFF;
  12. // I could write a wall of text here to explain... but TL;DW
  13. // Go read the ATmega32u4 datasheet.
  14. // And this: http://blog.saikoled.com/post/43165849837/secret-konami-cheat-code-to-high-resolution-pwm-on
  15. // Pin PB7 = OCR1C (Timer 1, Channel C)
  16. // Compare Output Mode = Clear on compare match, Channel C = COM1C1=1 COM1C0=0
  17. // (i.e. start high, go low when counter matches.)
  18. // WGM Mode 14 (Fast PWM) = WGM13=1 WGM12=1 WGM11=1 WGM10=0
  19. // Clock Select = clk/1 (no prescaling) = CS12=0 CS11=0 CS10=1
  20. TCCR1A = _BV(COM1C1) | _BV(WGM11); // = 0b00001010;
  21. TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS10); // = 0b00011001;
  22. backlight_init();
  23. }
  24. void backlight_set(uint8_t level)
  25. {
  26. if ( level == 0 )
  27. {
  28. // Turn off PWM control on PB7, revert to output low.
  29. TCCR1A &= ~(_BV(COM1C1));
  30. CHANNEL = 0x0;
  31. // Prevent backlight blink on lowest level
  32. PORTB &= ~(_BV(PORTB7));
  33. }
  34. else if ( level == BACKLIGHT_LEVELS )
  35. {
  36. // Prevent backlight blink on lowest level
  37. PORTB &= ~(_BV(PORTB7));
  38. // Turn on PWM control of PB7
  39. TCCR1A |= _BV(COM1C1);
  40. // Set the brightness
  41. CHANNEL = 0xFFFF;
  42. }
  43. else
  44. {
  45. // Prevent backlight blink on lowest level
  46. PORTB &= ~(_BV(PORTB7));
  47. // Turn on PWM control of PB7
  48. TCCR1A |= _BV(COM1C1);
  49. // Set the brightness
  50. CHANNEL = 0xFFFF >> ((BACKLIGHT_LEVELS - level) * ((BACKLIGHT_LEVELS + 1) / 2));
  51. }
  52. }