- // First, correlate for SOF
- for(i = 0; i < 200; i++) { // usually, SOF is found around i = 60
- int corr = 0;
- for(j = 0; j < arraylen(FrameSOF); j += skip) {
- corr += FrameSOF[j]*dest[i+(j/skip)];
- }
- if(corr > max) {
- max = corr;
- maxPos = i;
- }
+ if (Demod->posCount == 8) {
+ int16_t corr_1 = (Demod->sum2 - Demod->sum1) / 4;
+ int16_t corr_0 = (Demod->sum1 - Demod->sum2) / 4;
+ int16_t corr_EOF = (Demod->sum1 + Demod->sum2) / 8;
+ if (corr_EOF > corr_0 && corr_EOF > corr_1) {
+ Demod->state = DEMOD_AWAIT_EOF;
+ } else if (corr_1 > corr_0) {
+ // logic 1
+ if (Demod->lastBit == SOF_PART1) { // still part of SOF
+ Demod->lastBit = SOF_PART2;
+ } else {
+ Demod->lastBit = LOGIC1;
+ Demod->shiftReg >>= 1;
+ Demod->shiftReg |= 0x80;
+ Demod->bitCount++;
+ if (Demod->bitCount == 8) {
+ Demod->output[Demod->len] = Demod->shiftReg;
+ Demod->len++;
+ Demod->bitCount = 0;
+ Demod->shiftReg = 0;
+ }
+ }
+ } else {
+ // logic 0
+ if (Demod->lastBit == SOF_PART1) { // incomplete SOF
+ Demod->state = DEMOD_UNSYNCD;
+ LED_C_OFF();
+ } else {
+ Demod->lastBit = LOGIC0;
+ Demod->shiftReg >>= 1;
+ Demod->bitCount++;
+ if (Demod->bitCount == 8) {
+ Demod->output[Demod->len] = Demod->shiftReg;
+ Demod->len++;
+ Demod->bitCount = 0;
+ Demod->shiftReg = 0;
+ }
+ }
+ }
+ Demod->posCount = 0;
+ }
+ Demod->posCount++;
+ break;
+
+ case DEMOD_AWAIT_EOF:
+ if (Demod->lastBit == LOGIC0) { // this was already part of EOF
+ LED_C_OFF();
+ return true;
+ } else {
+ Demod->state = DEMOD_UNSYNCD;
+ LED_C_OFF();
+ }
+ break;
+
+ default:
+ Demod->state = DEMOD_UNSYNCD;
+ LED_C_OFF();
+ break;