// Frequency Counter Lib example

/*
  Martin Nawrath KHM LAB3
  Kunsthochschule f¸r Medien Kˆln
  Academy of Media Arts
  http://www.khm.de
  http://interface.khm.de/index.php/labor/experimente/	
 */
 /*
 Hardware 74HC590
 /4      <-  QB  1    16  VCC
 /8      <-  QC  2    15  QA     -> /2
 /16     <-  QD  3    14  G      -> GND
 /32     <-  QE  4    13  RCK    <--        Input liegt mit 1Mega an GND
 /64     <-  QF  5    12  CCKEN  -> GND
 /128    <-  QG  6    11  CCK    <--
 /256    <-  QH  7    10  CCLR   VCC
            GND  8     9  RCO    offen          
 
 http://www.pjrc.com/teensy/td_libs_FreqCount.html
 Board	FrequencyInput Pin	Pins Unusable with analogWrite()
Arduino Uno	  5	          3, 9, 10, 11
 */

#include <FreqCounter.h>


unsigned long frq;
int cnt;
int pinLed=13;


//Motorsteuerung
const int r1Pin = 7;
const int r2Pin = 6;
boolean r1 = false;
boolean r2 = false;
boolean change = false;

void setup() {
  pinMode(r1Pin, OUTPUT);
  pinMode(r2Pin, OUTPUT);
  update();
  Serial.begin(115200);        // connect to the serial port
  //Serial.println("Frequency Counter");
 
}



void loop() {

  // wait if any serial is going on
  FreqCounter::f_comp=8;   // Cal Value / Calibrate with professional Freq Counter
  FreqCounter::start(100);  // 100 ms Gate Time

  while (FreqCounter::f_ready == 0) 
  frq=FreqCounter::f_freq;
  Serial.print('>');
  Serial.print(frq);
  Serial.print('<');
 if (change) {
   char c = update();
    Serial.println(c);
    change = false;
  }
}  

char update(){
  char c=65;
  if(r1==true){
    digitalWrite(r1Pin,LOW);
        c++;
    } else {
    digitalWrite(r1Pin,HIGH);

    }
  if(r2==true){
    digitalWrite(r2Pin,LOW);
        c++;
    } else {
    digitalWrite(r2Pin,HIGH);
    }  
  return c;  
}
/*
  SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read(); 
    if (inChar == '0'){
      r1= false;
      r2= false;      
      change = true;

      }
    if (inChar == '1') {
      r1= true;
      r2= false;      
      change = true;
    } 
       if (inChar == '2') {
      r1= false;
      r2= true;
      change = true;
    } 
       if (inChar == '3') {
      r1= true;
      r2= true;
      change = true;
    } 
  }
}


