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.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. void sleep_led_toggle(void)
  44. {
  45. /* Disable Compare Match Interrupt */
  46. TIMSK1 ^= _BV(OCIE1A);
  47. }
  48. /* Breathing Sleep LED brighness(PWM On period) table
  49. * (64[steps] * 4[duration]) / 64[PWM periods/s] = 4 second breath cycle
  50. *
  51. * http://www.wolframalpha.com/input/?i=%28sin%28+x%2F64*pi%29**8+*+255%2C+x%3D0+to+63
  52. * (0..63).each {|x| p ((sin(x/64.0*PI)**8)*255).to_i }
  53. */
  54. static const uint8_t breathing_table[64] PROGMEM = {
  55. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 4, 6, 10,
  56. 15, 23, 32, 44, 58, 74, 93, 113, 135, 157, 179, 199, 218, 233, 245, 252,
  57. 255, 252, 245, 233, 218, 199, 179, 157, 135, 113, 93, 74, 58, 44, 32, 23,
  58. 15, 10, 6, 4, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  59. };
  60. ISR(TIMER1_COMPA_vect)
  61. {
  62. /* Software PWM
  63. * timer:1111 1111 1111 1111
  64. * \_____/\/ \_______/____ count(0-255)
  65. * \ \______________ duration of step(4)
  66. * \__________________ index of step table(0-63)
  67. */
  68. static union {
  69. uint16_t row;
  70. struct {
  71. uint8_t count:8;
  72. uint8_t duration:2;
  73. uint8_t index:6;
  74. } pwm;
  75. } timer = { .row = 0 };
  76. timer.row++;
  77. // LED on
  78. if (timer.pwm.count == 0) {
  79. led_set(1<<USB_LED_CAPS_LOCK);
  80. }
  81. // LED off
  82. if (timer.pwm.count == pgm_read_byte(&breathing_table[timer.pwm.index])) {
  83. led_set(0);
  84. }
  85. }