#include "FastLED.h"

#define NUM_PLATES 4
#define fs 40 //sampling frequency is in Hertz - change as needed
#define TS 1000000/(fs*NUM_PLATES)
//sampling period is 1/sampling frequency and sampling frequency is 40hz*num_plates and
//TS = us microseconds
#define DATA_PIN SPI_DATA //this is pin number 11 for the Arduino UNO (green is data)
#define CLOCK_PIN SPI_CLOCK //this is pin number 13 for the Arduino UNO (yellow is clock)
#define ET 500 //ET = exposure time in microseconds (us) you never want to over-expose your shot

/*
simple Arduino code for switching LEDs and triggering a machine vision camera for SSHTS imaging.
Upload the code and open the serial monitor in the Arduino IDE to control the LEDs
         type 'enter' in serial monitor to cycle between modes 
         mode 1,2,3,4 = LED 1,2,3 or 4 continuously on for focusing, 
         mode 5 = cycle between LEDs while triggering the camera
*/

int CameraOut = 7;

// Define the array of leds
CRGB leds[256];

// define location of LEDS here
int l1=4*16+11;    //4 11
int l2=8*16+3;     //8  4
int l3=4*16+3;     //4  3
int l4=8*16+11;    //8 11


void setup() {
  pinMode(CameraOut,OUTPUT);
  Serial.begin(115200);
  LEDS.addLeds<APA102,DATA_PIN,CLOCK_PIN,BGR>(leds,256);   
}

void toggle(){
      //switches on the LED then sends a trigger pulse to the camera to take a picture for ET microseconds, then wait until end of period (TS)
      FastLED.show();
      digitalWrite(CameraOut, HIGH);
      delayMicroseconds(ET);
      digitalWrite(CameraOut, LOW);   
      delayMicroseconds(TS-ET);
}

uint32_t pixel = 0;
int LEDfocus=0;
void loop() {
    
     if (Serial.available() > 0) {
     // read incoming serial data:
       char inChar = Serial.read();
       LEDfocus+=1;
       if (LEDfocus>=5) LEDfocus=0;
     }
     //reset all LEDs to black
     leds[l1] = CRGB::Black;
     leds[l2] = CRGB::Black;
     leds[l3] = CRGB::Black;
     leds[l4] = CRGB::Black;
    
     if (LEDfocus<4){
       //focusing mode
       if (LEDfocus==0) leds[l1]=CRGB::Red;
       if (LEDfocus==1) leds[l2]=CRGB::Red;
       if (LEDfocus==2) leds[l3]=CRGB::Red;
       if (LEDfocus==3) leds[l4]=CRGB::Red;
       FastLED.show();  
    }
    if (LEDfocus==4){
      leds[l4]=CRGB::Black;
      leds[l1]=CRGB::Red;
      toggle();
      leds[l1]=CRGB::Black;
      leds[l2]=CRGB::Red;
      toggle();
      leds[l2]=CRGB::Black;
      leds[l3]=CRGB::Red;
      toggle();
      leds[l3]=CRGB::Black;
      leds[l4]=CRGB::Red;
      toggle();
    }
    
} //end void loop
