indicator_leds.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. Copyright 2016-2017 Ralf Schmitt <ralf@bunkertor.net> Rasmus Schults <rasmusx@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. #define T1H 900
  19. #define T1L 600
  20. #define T0H 400
  21. #define T0L 900
  22. #define RES 6000
  23. #define NS_PER_SEC (1000000000L)
  24. #define CYCLES_PER_SEC (F_CPU)
  25. #define NS_PER_CYCLE (NS_PER_SEC / CYCLES_PER_SEC)
  26. #define NS_TO_CYCLES(n) ((n) / NS_PER_CYCLE)
  27. void send_bit_d4(bool bitVal) {
  28. if(bitVal) {
  29. asm volatile (
  30. "sbi %[port], %[bit] \n\t"
  31. ".rept %[onCycles] \n\t"
  32. "nop \n\t"
  33. ".endr \n\t"
  34. "cbi %[port], %[bit] \n\t"
  35. ".rept %[offCycles] \n\t"
  36. "nop \n\t"
  37. ".endr \n\t"
  38. ::
  39. [port] "I" (_SFR_IO_ADDR(PORTD)),
  40. [bit] "I" (4),
  41. [onCycles] "I" (NS_TO_CYCLES(T1H) - 2),
  42. [offCycles] "I" (NS_TO_CYCLES(T1L) - 2));
  43. } else {
  44. asm volatile (
  45. "sbi %[port], %[bit] \n\t"
  46. ".rept %[onCycles] \n\t"
  47. "nop \n\t"
  48. ".endr \n\t"
  49. "cbi %[port], %[bit] \n\t"
  50. ".rept %[offCycles] \n\t"
  51. "nop \n\t"
  52. ".endr \n\t"
  53. ::
  54. [port] "I" (_SFR_IO_ADDR(PORTD)),
  55. [bit] "I" (4),
  56. [onCycles] "I" (NS_TO_CYCLES(T0H) - 2),
  57. [offCycles] "I" (NS_TO_CYCLES(T0L) - 2));
  58. }
  59. }
  60. void show(void) {
  61. _delay_us((RES / 1000UL) + 1);
  62. }
  63. void send_value(uint8_t byte) {
  64. for(uint8_t b = 0; b < 8; b++) {
  65. send_bit_d4(byte & 0b10000000);
  66. byte <<= 1;
  67. }
  68. }
  69. void send_color(uint8_t r, uint8_t g, uint8_t b) {
  70. send_value(g);
  71. send_value(r);
  72. send_value(b);
  73. }
  74. void indicator_leds_set(bool leds[8]) {
  75. cli();
  76. send_color(leds[1] ? 255 : 0, leds[2] ? 255 : 0, leds[0] ? 255 : 0);
  77. send_color(leds[4] ? 255 : 0, leds[5] ? 255 : 0, leds[3] ? 255 : 0);
  78. send_color(leds[6] ? 255 : 0, leds[7] ? 255 : 0, 0);
  79. sei();
  80. show();
  81. }