indicator_leds.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. Copyright 2017 MechMerlin <mechmerlin@gmail.com>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <avr/interrupt.h>
  15. #include <avr/io.h>
  16. #include <stdbool.h>
  17. #include <util/delay.h>
  18. #include "indicator_leds.h"
  19. #define RES 6000
  20. #define LED_T1H 600
  21. #define LED_T1L 650
  22. #define LED_T0H 250
  23. #define LED_T0L 1000
  24. #define NS_PER_SEC (1000000000L)
  25. #define CYCLES_PER_SEC (F_CPU)
  26. #define NS_PER_CYCLE (NS_PER_SEC / CYCLES_PER_SEC)
  27. #define NS_TO_CYCLES(n) ((n) / NS_PER_CYCLE)
  28. void send_bit_d4(bool bitVal) {
  29. if(bitVal) {
  30. asm volatile (
  31. "sbi %[port], %[bit] \n\t"
  32. ".rept %[onCycles] \n\t"
  33. "nop \n\t"
  34. ".endr \n\t"
  35. "cbi %[port], %[bit] \n\t"
  36. ".rept %[offCycles] \n\t"
  37. "nop \n\t"
  38. ".endr \n\t"
  39. ::
  40. [port] "I" (_SFR_IO_ADDR(PORTD)),
  41. [bit] "I" (4),
  42. [onCycles] "I" (NS_TO_CYCLES(LED_T1H) - 2),
  43. [offCycles] "I" (NS_TO_CYCLES(LED_T1L) - 2));
  44. } else {
  45. asm volatile (
  46. "sbi %[port], %[bit] \n\t"
  47. ".rept %[onCycles] \n\t"
  48. "nop \n\t"
  49. ".endr \n\t"
  50. "cbi %[port], %[bit] \n\t"
  51. ".rept %[offCycles] \n\t"
  52. "nop \n\t"
  53. ".endr \n\t"
  54. ::
  55. [port] "I" (_SFR_IO_ADDR(PORTD)),
  56. [bit] "I" (4),
  57. [onCycles] "I" (NS_TO_CYCLES(LED_T0H) - 2),
  58. [offCycles] "I" (NS_TO_CYCLES(LED_T0L) - 2));
  59. }
  60. }
  61. void show(void) {
  62. _delay_us((RES / 1000UL) + 1);
  63. }
  64. void send_value(uint8_t byte) {
  65. for(uint8_t b = 0; b < 8; b++) {
  66. send_bit_d4(byte & 0b10000000);
  67. byte <<= 1;
  68. }
  69. }
  70. // Send the LED indicators to the WS2811S chips
  71. void indicator_leds_set(bool leds[8]) {
  72. uint8_t led_cnt;
  73. cli();
  74. for(led_cnt = 0; led_cnt < 8; led_cnt++)
  75. send_value(leds[led_cnt] ? 255 : 0);
  76. sei();
  77. show();
  78. }