#define hzclk 7
#define hzbinary 6
#define sigLED 11


uint8_t  hzclkval        = 0;
uint8_t  hzbinval[30];
uint8_t  clkval          = 0;
uint32_t milliscompare   = 0;
uint8_t  readyet         = 0;
uint8_t  x               = 0;
uint16_t mainsfreq       = 0;

struct {
   unsigned int mainstwo : 14;
} bitfieldA;

void setup() {
  // put your setup code here, to run once:


pinMode(hzclk, INPUT);
pinMode(hzbinary, INPUT);
pinMode(sigLED, OUTPUT);

Serial.begin(115200);
}

void loop() {


 if(digitalRead(hzbinary) == LOW){
  //this handles one clk cycle each
  //need to read 20 cycles
  clkval = 0;
  checkCLKandBIN();checkCLKandBIN();checkCLKandBIN();
  checkCLKandBIN();checkCLKandBIN();checkCLKandBIN();
  checkCLKandBIN();checkCLKandBIN();checkCLKandBIN();
  checkCLKandBIN();checkCLKandBIN();checkCLKandBIN();
  checkCLKandBIN();checkCLKandBIN();checkCLKandBIN();
  checkCLKandBIN();
  checkCLKandBIN();
  checkCLKandBIN();
  checkCLKandBIN();
  checkCLKandBIN();
  checkCLKandBIN();
  checkCLKandBIN();
  //Serial.println(clkval); //outputs 19 or 20
  ConvertArraytoBin();
   mainsfreq = 0;
   bitfieldA.mainstwo = 0;
 }
 delayMicroseconds(100); //must be lower than 1 millisecond, so mic
  /*if hzbinary is low
   * 
   * while clk high, do nothing
   * clk++
   * sample hzbinary
   * while clk low do nothing
   */
   /*
    * //serial print is very slow, and breaks timing
    * the below is not usable
    * (DMA anyone? second processor anyone?)
   Serial.println("hzbinval 1 - 20:");
   for(x=0;x<21;x++){
    Serial.println(hzbinval[x]);
   }
   Serial.print("\n\n\n\n");
   */
   
   

//sample on falling edge (middle of bit)
}
void checkCLKandBIN(void){
  /*
   * while clk high, do nothing
   * clk++
   * sample hzbinary
   * while clk low do nothing
   */
   //milliscompare = millis();
   while((hzclkval = digitalRead(hzclk)) == HIGH){
    if(readyet == 0){
      hzbinval[clkval] = digitalRead(hzbinary);
      clkval++;
      readyet = 1;
    }
    delayMicroseconds(10);
   }
   while((hzclkval = digitalRead(hzclk)) == LOW){
    delayMicroseconds(1);
    readyet = 0;
    }
   //digitalWrite(sigLED, HIGH);
   //delayMicroseconds(1);
   //digitalWrite(sigLED, LOW);
   

   //would be nice to add a picture to this source code (waveform)
   //or oscope picture
   //why isn't this possible?
  
}

void ConvertArraytoBin (void){
   for(x=3;x<21;x++){
    if(hzbinval[x] == 1){
      bitfieldA.mainstwo = bitfieldA.mainstwo | (0b0000000000000000000001 << (x - 3));
    }
   }
   Serial.println(bitfieldA.mainstwo,BIN);
   
   /*mainsfreq = mainsfreq >> 3;
   mainsfreq = mainsfreq & 0b0111111111111;
  Serial.println(mainsfreq,DEC);
  //111011011101
  //1011101101111
  //111011011101
  //11101101111*/



}


