- int lastBit = 0; //set first clock check
- size_t iii = 0, bitnum = 0; //bitnum counter
- uint16_t errCnt = 0, MaxBits = 1000;
- size_t bestErrCnt = maxErr+1;
- size_t bestPeakCnt = 0, bestPeakStart = 0;
- uint8_t bestFirstPeakHigh=0, firstPeakHigh=0, curBit=0, bitHigh=0, errBitHigh=0;
- uint8_t tol = 1; //clock tolerance adjust - waves will be accepted as within the clock if they fall + or - this value + clock from last valid wave
- uint16_t peakCnt=0;
- uint8_t ignoreWindow=4;
- uint8_t ignoreCnt=ignoreWindow; //in case of noise near peak
- //loop to find first wave that works - align to clock
- for (iii=0; iii < gLen; ++iii){
- if ((dest[iii]>=high) || (dest[iii]<=low)){
- if (dest[iii]>=high) firstPeakHigh=1;
- else firstPeakHigh=0;
- lastBit=iii-*clk;
- peakCnt=0;
- errCnt=0;
- //loop through to see if this start location works
- for (i = iii; i < *size; ++i) {
- // if we are at a clock bit
- if ((i >= lastBit + *clk - tol) && (i <= lastBit + *clk + tol)) {
- //test high/low
- if (dest[i] >= high || dest[i] <= low) {
- bitHigh = 1;
- peakCnt++;
- errBitHigh = 0;
- ignoreCnt = ignoreWindow;
- lastBit += *clk;
- } else if (i == lastBit + *clk + tol) {
- lastBit += *clk;
- }
- //else if no bars found
- } else if (dest[i] < high && dest[i] > low){
- if (ignoreCnt==0){
- bitHigh=0;
- if (errBitHigh==1) errCnt++;
- errBitHigh=0;
- } else {
- ignoreCnt--;
- }
- } else if ((dest[i]>=high || dest[i]<=low) && (bitHigh==0)) {
- //error bar found no clock...
- errBitHigh=1;
- }
- if (((i-iii) / *clk)>=MaxBits) break;
- }
- //we got more than 64 good bits and not all errors
- if (((i-iii) / *clk) > 64 && (errCnt <= (maxErr))) {
- //possible good read
- if (!errCnt || peakCnt > bestPeakCnt){
- bestFirstPeakHigh=firstPeakHigh;
- bestErrCnt = errCnt;
- bestPeakCnt = peakCnt;
- bestPeakStart = iii;
- if (!errCnt) break; //great read - finish
- }
- }
- }