#include <Wire.h>
#define WIRE Wire

uint8_t readBuffer[256]="";
#define TCR_ADDRESS 12
int i;
int lastSize=-1;
int size=0;
unsigned long lastCodeTime=0;
#define TIMEOUT 2000

void setup() {
  Serial.begin(115200);
  while(!Serial) {} //wait for serial port to connect
  WIRE.setSDA(0);
  WIRE.setSCL(1);
  WIRE.begin();
  WIRE.setClock(100000);
  delay(2000);
  Serial.println("Start");
  Serial.println("The Tiny QR Code Reader should be at address 0x0C");
  runI2Cscan();
}

void loop() {
  int d;
  readBuffer[0]=0;
  readBuffer[1]=0;  //ensure blank until data read
  WIRE.readAsync(TCR_ADDRESS, readBuffer, sizeof(readBuffer),true); //true= send stop
  delay(200);   //reasonable time to finish
  if(WIRE.finishedAsync()){
    size=readBuffer[1];
    size=size*256;
    size=size+readBuffer[0]; //shouldn't be more than 254, but it is a 16-bit value
    if(size>254){size=254;}  
  }else{
    size=-1;
    WIRE.abortAsync();
  }
  if((size!=lastSize) || ((millis()-lastCodeTime)>TIMEOUT)){
    lastCodeTime=millis();
    if(size>0){
      Serial.println("Code detected:");
      for(i=0;i<size;i++){Serial.write((char)readBuffer[i+2]);}
      Serial.println();
    }else if(size<0){
      Serial.println("Comms error.");
    }else{
      Serial.println("No code detected.");
    }
  }
  lastSize=size;
  if(Serial.available()){
    d=Serial.read();
    if(d=='0'){sendI2Ccmd(TCR_ADDRESS,1,0);Serial.println("LED off");}
    if(d=='1'){sendI2Ccmd(TCR_ADDRESS,1,1);Serial.println("LED on");}
  }
}

void sendI2Ccmd(byte a, byte c, byte d){
  WIRE.beginTransmission(a);
  WIRE.write(c);
  WIRE.write(d);
  WIRE.endTransmission();  
}

byte runI2Cscan(void){
  byte i;
  byte count=0;
  for (byte i = 8; i < 120; i++){
    WIRE.beginTransmission (i);
    if (WIRE.endTransmission () == 0){
      Serial.print ("Found 7 bit address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");

      Serial.print ("      8 bit write address: ");
      Serial.print (i*2, DEC);
      Serial.print (" (0x");
      Serial.print (i*2, HEX);
      Serial.println (")");

      Serial.print ("      8 bit read address: ");
      Serial.print (i*2+1, DEC);
      Serial.print (" (0x");
      Serial.print (i*2+1, HEX);
      Serial.println (")");
      count++;
      delay (1);  // maybe unneeded?
      } // end of good response
  } // end of for loop
  Serial.println ("Done.");
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");
  Serial.print("T=");
  Serial.println(millis(),DEC);
  return count;
}

