clas_o_sensor.ino 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. //#define CLAS_O_DEBUG
  2. namespace clas_o {
  3. enum { UNKNOWN, T0, T1, T2, T3, OK, DONE };
  4. unsigned char state = UNKNOWN;
  5. uint32_t x_data;
  6. uint8_t x_numBits;
  7. void resetDecoder () {
  8. x_data = 0;
  9. x_numBits = 0;
  10. state = UNKNOWN;
  11. }
  12. static boolean isDone() {
  13. return state == DONE;
  14. }
  15. static void done () {
  16. state = DONE;
  17. }
  18. static void gotBit (uint8_t value) {
  19. x_numBits++;
  20. x_data = (x_data << 1) + (value & 0x01);
  21. state = OK;
  22. }
  23. static int16_t decode (uint16_t width) {
  24. if( state != UNKNOWN ) {
  25. #ifdef CLAS_O_DEBUG
  26. Serial.print(width);
  27. Serial.print(" - ");
  28. #endif
  29. }
  30. switch (state) {
  31. case UNKNOWN: // Start of frame
  32. if ( (3500) <= width && width <= (4000) ) {
  33. #ifdef CLAS_O_DEBUG
  34. Serial.print(width);
  35. Serial.print(" - ");
  36. #endif
  37. state = T0;
  38. }
  39. else {
  40. return -1; // error, reset
  41. }
  42. break;
  43. case T0: // First half of pulse : HIGH around 230us
  44. if ( x_numBits == 32 ) { // end of frame
  45. state = DONE;
  46. x_data = (x_data >> 8); // Mask away some bits at the end
  47. return 1;
  48. }
  49. else if ( 340 <= width && width <= 560 ) {
  50. state = T1;
  51. }
  52. else {
  53. if ( x_numBits == 0 && (3500 <= width && width <= 4000) ) {
  54. state = T0;
  55. }
  56. else {
  57. #ifdef CLAS_O_DEBUG
  58. Serial.println(" X1X ");
  59. #endif
  60. return -1; // error, reset
  61. }
  62. }
  63. break;
  64. case T1:
  65. if ( 800 <= width && width <= 1000 ) {
  66. gotBit(0);
  67. } else if ( 1640 <= width && width <= 1940 ) {
  68. gotBit(1);
  69. } else {
  70. #ifdef CLAS_O_DEBUG
  71. Serial.println(" X2X ");
  72. #endif
  73. return -1; // error, reset
  74. }
  75. state = T0;
  76. break;
  77. }
  78. return 0;
  79. }
  80. boolean nextPulse( uint16_t width ) {
  81. if ( width > 0 ) {
  82. if (state != DONE)
  83. switch (decode(width)) {
  84. case -1:
  85. resetDecoder();
  86. break;
  87. case 1: done(); break;
  88. }
  89. }
  90. return isDone();
  91. }
  92. }