nexa.ino 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. enum { UNKNOWN, T0, T1, T2, T3, OK, DONE };
  2. byte state = UNKNOWN;
  3. unsigned long x_data;
  4. static unsigned int x_numBits;
  5. static boolean x_2ndbit;
  6. static unsigned int dbg_periodTime; // For debugging
  7. static void resetDecoder () {
  8. x_data = 0;
  9. x_numBits = 0;
  10. x_2ndbit = false;
  11. state = UNKNOWN;
  12. }
  13. static boolean isDone() { return state == DONE; }
  14. static void done () { state = DONE; }
  15. static void gotBit (char value) {
  16. // X
  17. x_numBits++;
  18. x_data = (x_data << 1) + (value & 0x01);
  19. if( x_2ndbit == false ) {
  20. x_2ndbit = true;
  21. }
  22. else {
  23. x_2ndbit = false;
  24. unsigned int bits = (x_data & 0x03);
  25. if( bits == 2 ) {
  26. // Bit is 1
  27. x_data = (x_data >> 1) | 0x00000001;
  28. }
  29. else {
  30. // Bit is 0
  31. x_data = (x_data >> 1) & 0xFFFFFFFE;
  32. }
  33. }
  34. state = OK;
  35. }
  36. static int decode (unsigned int width) {
  37. switch (state) {
  38. case UNKNOWN: // Start of frame
  39. //printf("%8u\n",width);
  40. if ( 2400 <= width && width <= 3000 ) {
  41. state = T0;
  42. //dbg_periodTime = width;
  43. }
  44. break;
  45. case T0: // First half of pulse : HIGH around 230us
  46. if ( 150 <= width && width <= 300 ) {
  47. state = T1;
  48. }
  49. else if ( x_numBits == 0 && 2400 <= width && width <= 3000 ) {
  50. state = T0;
  51. }
  52. else return -1; // error, reset
  53. break;
  54. case T1:
  55. if ( 200 <= width && width <= 400) {
  56. gotBit(0);
  57. } else if ( 1000 <= width && width <= 1500 ) {
  58. gotBit(1);
  59. } else if ( /*width > 5000 &&*/ x_numBits == 64) { // end of frame
  60. state = DONE;
  61. return 1;
  62. } else {
  63. return -1;
  64. }
  65. state = T0;
  66. break;
  67. }
  68. return 0;
  69. }
  70. #define TOO_SHORT 100
  71. bool nextPulseNexa (unsigned int width) {
  72. if( width > 0 ) {
  73. if (state != DONE)
  74. switch (decode(width)) {
  75. case -1:
  76. resetDecoder();
  77. break;
  78. case 1: done(); break;
  79. }
  80. }
  81. return isDone();
  82. }