//Arduino sketch to emulate the 9600 baud HEX mode of the LED TREE CONTROL PCB

//pin defines can be changed- these are the same order as the LED TREE CONTROL PCB
#define DI_PIN 2
#define DO_PIN 3
#define LT_PIN 4
#define CK_PIN 5

char hex[17]="0123456789ABCDEF";

void setup() {
  Serial.begin(9600);   //in case we connect to a physical (non virtual) UART
  pinMode(DI_PIN,OUTPUT);
  digitalWrite(DI_PIN,LOW);
  pinMode(LT_PIN,OUTPUT);
  digitalWrite(LT_PIN,LOW);
  pinMode(CK_PIN,OUTPUT);
  digitalWrite(CK_PIN,LOW);
  pinMode(DO_PIN,INPUT); 
}

void loop() {
  int d;
  while(Serial.available()){
    d=Serial.read();
    switch(d){
      case 'v': digitalWrite(LT_PIN,LOW);break;
      case 'V': digitalWrite(LT_PIN,HIGH);Serial.println();break;   //break serial monitor lines by transfer
      case '0': shiftNybble(0);break;
      case '1': shiftNybble(1);break;
      case '2': shiftNybble(2);break;
      case '3': shiftNybble(3);break;
      case '4': shiftNybble(4);break;
      case '5': shiftNybble(5);break;
      case '6': shiftNybble(6);break;
      case '7': shiftNybble(7);break;
      case '8': shiftNybble(8);break;
      case '9': shiftNybble(9);break;
      case 'A': shiftNybble(10);break;
      case 'B': shiftNybble(11);break;
      case 'C': shiftNybble(12);break;
      case 'D': shiftNybble(13);break;
      case 'E': shiftNybble(14);break;
      case 'F': shiftNybble(15);break;
      case 'a': shiftNybble(10);break;
      case 'b': shiftNybble(11);break;
      case 'c': shiftNybble(12);break;
      case 'd': shiftNybble(13);break;
      case 'e': shiftNybble(14);break;
      case 'f': shiftNybble(15);break;
    }
  }
}

void shiftNybble(char c){
  char d0result=0;
  digitalWrite(DI_PIN,c&8);
  d0result=d0result+8*digitalRead(DO_PIN);
  digitalWrite(CK_PIN,HIGH);
  digitalWrite(CK_PIN,LOW);
  digitalWrite(DI_PIN,c&4);
  d0result=d0result+4*digitalRead(DO_PIN);
  digitalWrite(CK_PIN,HIGH);
  digitalWrite(CK_PIN,LOW);
  digitalWrite(DI_PIN,c&2);
  d0result=d0result+2*digitalRead(DO_PIN);
  digitalWrite(CK_PIN,HIGH);
  digitalWrite(CK_PIN,LOW);
  digitalWrite(DI_PIN,c&1);
  d0result=d0result+1*digitalRead(DO_PIN);
  digitalWrite(CK_PIN,HIGH);
  digitalWrite(CK_PIN,LOW);
  Serial.write(hex[d0result]);
}

