Keyboard firmwares for Atmel AVR and Cortex-M
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sleep_led.c 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include <stdint.h>
  2. #include <avr/io.h>
  3. #include <avr/interrupt.h>
  4. #include <avr/pgmspace.h>
  5. #include "led.h"
  6. #include "sleep_led.h"
  7. /* Software PWM
  8. * ______ ______ __
  9. * | ON |___OFF___| ON |___OFF___| ....
  10. * |<-------------->|<-------------->|<- ....
  11. * PWM period PWM period
  12. *
  13. * 256 interrupts/period[resolution]
  14. * 64 periods/second[frequency]
  15. * 256*64 interrupts/second
  16. * F_CPU/(256*64) clocks/interrupt
  17. */
  18. #define SLEEP_LED_TIMER_TOP F_CPU/(256*64)
  19. void sleep_led_init(void)
  20. {
  21. /* Timer1 setup */
  22. /* CTC mode */
  23. TCCR1B |= _BV(WGM12);
  24. /* Clock selelct: clk/1 */
  25. TCCR1B |= _BV(CS10);
  26. /* Set TOP value */
  27. uint8_t sreg = SREG;
  28. cli();
  29. OCR1AH = (SLEEP_LED_TIMER_TOP>>8)&0xff;
  30. OCR1AL = SLEEP_LED_TIMER_TOP&0xff;
  31. SREG = sreg;
  32. }
  33. void sleep_led_enable(void)
  34. {
  35. /* Enable Compare Match Interrupt */
  36. TIMSK1 |= _BV(OCIE1A);
  37. }
  38. void sleep_led_disable(void)
  39. {
  40. /* Disable Compare Match Interrupt */
  41. TIMSK1 &= ~_BV(OCIE1A);
  42. }
  43. /* Breathing Sleep LED brighness(PWM On period) table
  44. * (32[steps] * 8[duration]) / 64[PWM periods/s] = 4 second breath cycle
  45. */
  46. static const uint8_t breathing_table[32] PROGMEM = {
  47. 0, 0, 0, 2, 9, 21, 37, 56, 78, 127, 151, 175, 197, 216, 232, 244,
  48. 254, 244, 216, 197, 175, 151, 127, 78, 56, 37, 21, 9, 2, 0, 0, 0
  49. };
  50. ISR(TIMER1_COMPA_vect)
  51. {
  52. /* Software PWM
  53. * timer:1111 1111 1111 1111
  54. * \----/\-/ \-------/+--- count(0-255)
  55. * | +--------------- duration of step(8)
  56. * +-------------------- index of step table(0-31)
  57. */
  58. static union {
  59. uint16_t row;
  60. struct {
  61. uint8_t count:8;
  62. uint8_t duration:3;
  63. uint8_t index:5;
  64. } pwm;
  65. } timer = { .row = 0 };
  66. timer.row++;
  67. // LED on
  68. if (timer.pwm.count == 0) {
  69. led_set(1<<USB_LED_CAPS_LOCK);
  70. }
  71. // LED off
  72. if (timer.pwm.count == pgm_read_byte(&breathing_table[timer.pwm.index])) {
  73. led_set(0);
  74. }
  75. }