/*
 Flash Delay for Stereo Camera Rigs
 
 Description:
 When the shutter release is pressed, a delay timer is started
 and when expired, then fires an external flash while the shutters
 are open on both cameras.
 Note:
 The delay timer is activated by a "transition to ground" signal
 
 This code is in the public domain.
 */

// Initial  varible settings for the delayed flash
int FlashDelay = 0;
int shutterRelease = 1;
int potValue = 0;

// Power/CPU activity indiicator
// These variables store the flash pattern
// and the current state of the LED

int ledPin = 2;      // the number of the LED pin
int ledState = LOW;             // ledState used to set the LED
unsigned long previousMillis = 0;        // will store last time LED was updated
long OnTime = 75;           // milliseconds of on-time
long OffTime = 5000;          // milliseconds of off-time



void setup() {               
  // initialize the digital pin as an output for flash
  pinMode(0, OUTPUT);
 
  // initialize the shutter pin as an input for shutter release ground signal
  pinMode(1, INPUT_PULLUP);

  // set the digital pin as output for CPU activity LED
  pinMode(ledPin, OUTPUT);

  // initially turn on Activity LED upon switching on
   digitalWrite(ledPin, HIGH);
   delay(1500);
   digitalWrite(ledPin, LOW);

}

void loop() {
 
  //this reading is used to determine the legnth of the delay
  //in the upcoming if/else conditional statement
  potValue = analogRead(3);
 
  //if the potentiometer value is over 20, divide by 20
  //this constrains the 0 to 1023 reading to roughly
  //0ms to 51ms delay time. Centering the trim pot
  //should result in a 26ms (.026 second) delay time
 
  if(potValue > 19){
    FlashDelay = (potValue / 20);
  }
  else{
    FlashDelay = 0;
  }
 
  //checks to see if a picture has been taken
  shutterRelease = digitalRead(1);
 
  //upon the shutter release, the flash is triggered
  //with whatever length of delay you set with the trim pot
  if(shutterRelease == 0){
    delay(FlashDelay);
    digitalWrite(0, HIGH);
    delay(50);
    digitalWrite(0, LOW);
    //wait for flash to reset
    delay(4800);
  }

  // check to see if it's time to change the state of the  activity LED
  unsigned long currentMillis = millis();
 
  if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
  {
    ledState = LOW;  // Turn it off
    previousMillis = currentMillis;  // Remember the time
    digitalWrite(ledPin, ledState);  // Update the actual LED
  }
  else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
  {
    ledState = HIGH;  // turn it on
    previousMillis = currentMillis;   // Remember the time
    digitalWrite(ledPin, ledState);    // Update the actual Activity LED
  }
}