Hi
A couple of minor changes. I've commented them, and hope this does what you intend, which is (as I understand it)
- Count revolutions
- After the 2nd revolution, turn a LED on for a duration set by a potentiometer
- After the LED has been on for the duration, turn it off
- Rinse, repeat
If this is the case, something like this might do the trick:
const int IR = 2; // IR input
const int ledPin = 3; // Injector SSR
int load = A0 ; // Analog input to increase or decrease how long the injctor stays energized
int ledState = LOW;
int IRCounter = 0;
int IRState = 0;
int lastIRState = 0;
long previousMillis = 0;
long interval = 0;
void setup() {
pinMode(IR, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
// check iR sensor and update counter if it sees the trigger
IRState = digitalRead(IR);
if (IRState != lastIRState) {
if (IRState == HIGH) {
IRCounter++;
Serial.println("on");
Serial.print("IR triggers: ");
Serial.println(IRCounter);
}
else Serial.println("off");
}
lastIRState = IRState;
// Check to see if you need to update the LED (only occurs after the 2nd rotation detected)
if (IRCounter >= 2) { // If we're on or after 2nd count
if(ledState == LOW) { // we've not turned it on yet
ledState = HIGH; // set the state to on
previousMillis = millis(); // record when we turn the LED on
interval = analogRead(load); // read how long to leave it on for
}
else { // else, the LED is already on
if(millis() - previousMillis >= interval) { // it's time to turn the LED off again
ledState = LOW; // set state to off
IRCounter=0; // reset the counter so it will start counting from 0 again
}
} // end of else
digitalWrite(ledPin, ledState);
}
}
Now the downside here is your IRCounter will be zeroed out when the LED has been on and is turned off. If you want to keep a total that keeps climbing you may need to consider a second counter, and maybe make it an unsigned int, unsigned long etc (ie a variable type that can deal with very large positive values) depending how long you want to run this.
Cheers !
Geoff