clas_o_sensor.ino 2.6 KB

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