#define SENSOR1_POWER_PIN     15    // Analog output pin A1
#define SENSOR1_APIN           2    // Analog input pin A2

// Inline AVR Assembler code
// cbi and sbi are standard (AVR) methods for setting, 
// or clearing, bits in PORT (and other) variables.
#ifndef cbi   // clear
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi   // set
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

int last_loop_light = 0;
int this_loop_light = 0; 
int threshold = 10;      // light change threshold

void setup()
{
  pinMode(SENSOR1_POWER_PIN, OUTPUT);    // pinmode for powering sensor
  digitalWrite(SENSOR1_POWER_PIN, LOW);  // set transistor base to LOW to switch power on
 
  Serial.begin(9600);  // uncomment for debugging
 
  // The ADPS are the bits to determine the division factor between the system 
  // clock frequency and the input clock to the AD converter.
  // Below, setting to 100 sets division factor to 16 (speed of AD conversion)

  sbi(ADCSRA,ADPS2) ;    // Set ADCSRA register, bit 2 (ADPS2) to 1
  cbi(ADCSRA,ADPS1) ;    // Set ADCSRA register, bit 1 (ADPS1) to 0
  cbi(ADCSRA,ADPS0) ;    // Set ADCSRA register, bit 0 (ADPS0) to 0

  
  DDRD = DDRB | B10000000; // initialize digital registers

  PORTD = B00000000;       // initialize digital pins 0-7 low
  
  last_loop_light = analogRead(SENSOR1_APIN);  // read light level
}

void loop() {

  this_loop_light = analogRead(SENSOR1_APIN);  // read light level
  
  if ((this_loop_light - last_loop_light) > threshold) // compare light levels
  {
    PORTD=B10000000; // set pin6/7 high (trigger camera)
    delay(100);      // wait 100ms
    PORTD=B00000000; // set pin7 low (reset trigger)
    
    // uncomment following for debugging:
    Serial.print("old:");
    Serial.print(last_loop_light,DEC);
    Serial.print(", new:");
    Serial.println(this_loop_light,DEC);
  }

  last_loop_light = this_loop_light;  // set current light level
}