+ break;
+
+ case STATE_READER_AWAIT_END_OF_SOF_1_OUT_OF_4:
+ DecodeReader->posCount++;
+ if (bit) {
+ if (DecodeReader->posCount == 9) {
+ DecodeReader->posCount = 1;
+ DecodeReader->bitCount = 0;
+ DecodeReader->byteCount = 0;
+ DecodeReader->sum1 = 1;
+ DecodeReader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_4;
+ LED_B_ON();
+ } else {
+ // do nothing, keep waiting
+ }
+ } else { // unexpected falling edge
+ DecodeReaderReset(DecodeReader);
+ }
+ break;
+
+ case STATE_READER_RECEIVE_DATA_1_OUT_OF_4:
+ DecodeReader->posCount++;
+ if (DecodeReader->posCount == 1) {
+ DecodeReader->sum1 = bit;
+ } else if (DecodeReader->posCount <= 4) {
+ DecodeReader->sum1 += bit;
+ } else if (DecodeReader->posCount == 5) {
+ DecodeReader->sum2 = bit;
+ } else {
+ DecodeReader->sum2 += bit;
+ }
+ if (DecodeReader->posCount == 8) {
+ DecodeReader->posCount = 0;
+ int corr10 = DecodeReader->sum1 - DecodeReader->sum2;
+ int corr01 = DecodeReader->sum2 - DecodeReader->sum1;
+ int corr11 = (DecodeReader->sum1 + DecodeReader->sum2) / 2;
+ if (corr01 > corr11 && corr01 > corr10) { // EOF
+ LED_B_OFF(); // Finished receiving
+ DecodeReaderReset(DecodeReader);
+ if (DecodeReader->byteCount != 0) {
+ return true;
+ }
+ }
+ if (corr10 > corr11) { // detected a 2bit position
+ DecodeReader->shiftReg >>= 2;
+ DecodeReader->shiftReg |= (DecodeReader->bitCount << 6);
+ }
+ if (DecodeReader->bitCount == 15) { // we have a full byte
+ DecodeReader->output[DecodeReader->byteCount++] = DecodeReader->shiftReg;
+ if (DecodeReader->byteCount > DecodeReader->byteCountMax) {
+ // buffer overflow, give up
+ LED_B_OFF();
+ DecodeReaderReset(DecodeReader);
+ }
+ DecodeReader->bitCount = 0;
+ DecodeReader->shiftReg = 0;
+ } else {
+ DecodeReader->bitCount++;
+ }
+ }
+ break;
+
+ case STATE_READER_RECEIVE_DATA_1_OUT_OF_256:
+ DecodeReader->posCount++;
+ if (DecodeReader->posCount == 1) {
+ DecodeReader->sum1 = bit;
+ } else if (DecodeReader->posCount <= 4) {
+ DecodeReader->sum1 += bit;
+ } else if (DecodeReader->posCount == 5) {
+ DecodeReader->sum2 = bit;
+ } else {
+ DecodeReader->sum2 += bit;
+ }
+ if (DecodeReader->posCount == 8) {
+ DecodeReader->posCount = 0;
+ int corr10 = DecodeReader->sum1 - DecodeReader->sum2;
+ int corr01 = DecodeReader->sum2 - DecodeReader->sum1;
+ int corr11 = (DecodeReader->sum1 + DecodeReader->sum2) / 2;
+ if (corr01 > corr11 && corr01 > corr10) { // EOF
+ LED_B_OFF(); // Finished receiving
+ DecodeReaderReset(DecodeReader);
+ if (DecodeReader->byteCount != 0) {
+ return true;
+ }
+ }
+ if (corr10 > corr11) { // detected the bit position
+ DecodeReader->shiftReg = DecodeReader->bitCount;
+ }
+ if (DecodeReader->bitCount == 255) { // we have a full byte
+ DecodeReader->output[DecodeReader->byteCount++] = DecodeReader->shiftReg;
+ if (DecodeReader->byteCount > DecodeReader->byteCountMax) {
+ // buffer overflow, give up
+ LED_B_OFF();
+ DecodeReaderReset(DecodeReader);
+ }
+ }
+ DecodeReader->bitCount++;
+ }
+ break;