NOOB question on resetting timer in loop.

Hi Guys,

This my first ever project. Trying to make a reflexes game where you must hit a Piezo within a set time (1000 ms currently) after a light comes on. I then want the loop to start again after a random pause. I have assigned a RGB LED to correspond to certain actions.

The program works fine for one cycle when the arduino is reset, but after that first loop cycle, it no longer responds. I think this is because my millis() equation is off.

I’ve searched the forum and tried to educate myself on the millis command, but after 2 days I can’t see what I’m doing wrong. Could you please help out a noob who bought his first board 3 days ago? :slight_smile:

THanks!

int redLedPin = 9; // RGB red LED pin 9
int greenLedPin = 10; // RGB green LED pin 10
int blueLedPin = 11; // RGB blue LED pin 11
int knock = 0; // Piezo sensor
unsigned long StartTime = millis();

void setup() {
pinMode (redLedPin, OUTPUT); //RGB LEN pins OUTPUTs
pinMode (greenLedPin, OUTPUT);
pinMode (blueLedPin, OUTPUT);

}

void loop()
{

unsigned long CurrentTime = millis();
unsigned long ElapsedTime = CurrentTime - StartTime;
analogWrite(blueLedPin, 255); // RGB LED is blue
analogWrite(greenLedPin, 0);
analogWrite(redLedPin, 0);
knock = analogRead(0); // Piezo on analog pin 0
if ((knock > 10)&&(ElapsedTime < 1000)) // If Piezo value is greater than 10 and Elapsed time from start of blue light is less than 1000 milliseconds, then:
{
analogWrite(blueLedPin, 0); // RGB LED turns green for 500 milliseconds
analogWrite(greenLedPin, 255);
analogWrite(redLedPin, 0);

delay(500);

analogWrite(blueLedPin, 0); //RGB LED turns yellow for 500 milliseconds
analogWrite(greenLedPin, 100);
analogWrite(redLedPin, 255);

delay(500);

analogWrite(blueLedPin, 0); // RGB LED turns red for a random time of between 1 and 5 seconds
analogWrite(greenLedPin, 0);
analogWrite(redLedPin, 255);

delay(random(1000, 5000));

}

}

Need to reset the start time for the next pass:

  if ((knock > 10)&&(ElapsedTime < 1000)) // If Piezo value is greater than 10 and Elapsed time from start of blue light is less than 1000 milliseconds, then:
  {
     StartTime = CurrentTime + (whatever time the event is to occur again - 1000 to 5000 later with your delays);
     // and continue ...

Thanks so much for the reply! I see what you mean, will this still work considering my delay times are random? I put that line in and still getting the same results :frowning: I also tried timing it using 'while', but that didn't work either. All I want is for the loop to work and the timer to reset..

Need to reset the start time for the next pass:

Except you should never add times. Rollover can happen.

Subtracting times (now - then) is guaranteed to work.