/**
 * Matthias Quintern, 2025
 * 
 * Simple Arduino program that listens via serial for single byte commands to control a ThorLabs LEDD1B
 * Commands:
 * - 'i': Identify - Prints "Arduino Nano CPD <version>"
 * - '0': Turn the LED off
 * - '1': Turn the LED on
 */
const int LEDPIN = 11;
const int VERSION = 1;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);
  Serial.begin(9600, SERIAL_8N1);  			//USB-Prog. Port
  while (!Serial) {
    ;  // wait for serial port to connect. Needed for native USB port only
  }
  pinMode(LEDPIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, LOW);

  if (Serial.available() <= 0) {
    return;
  }
  char command = Serial.read();
  digitalWrite(LED_BUILTIN, HIGH);
  switch (command) {
    case 'i':
      identify();
      break;
    case '1':
      Serial.println("LED ON");
      led_on();
      break;
    case '0':
      Serial.println("LED OFF");
      led_off();
      break;
    case '\n':
      break;
    default:
      blink_internal_led(5);
      break;
  }
}
void blink_internal_led(unsigned N) {
  unsigned long duration = 100;
  for (unsigned i = 0; i < N; i++) {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(duration);
    digitalWrite(LED_BUILTIN, LOW);
    delay(duration);
  }
}
void led_on() {
  digitalWrite(LEDPIN, HIGH);
}
void led_off() {
  digitalWrite(LEDPIN, LOW);
}

void identify() {
    Serial.print("Arduino Nano CPD ");
    Serial.print(VERSION);
    Serial.println("");
}