Keep reading soundsensor during the entire loop

Hi Guys,

At the moment i'm trying to build something like a policecar. My idea is to let hem just drive around and that works fine. But what i want to add next is that when i clap or make some other hard noise the policecar starts doing something else.

So far i figured out how to do that but there is 1 problem. What i want is de policecar to go back to normal when i clap again.

In short Policecar should start at status1, when i clap change to status2 and when i clap again go back to status1.

I have been searching for similar codes but can't find anything that i understand.

Hope you guys can help me (my current code is below).

int stat = 0;

void setup() {
  Serial.begin(9600);

  pinMode(12, OUTPUT); // Blue LED
  pinMode(13, OUTPUT); // Red LED
  
}

void loop() {
  int sound = analogRead(A5); // A5 is sound detector
  Serial.println(sound);
  delay(10);
  normal();
  police();
}

void normal(){
  int sound = analogRead(A5);
  if (stat%2 == 0){
    if (sound > 25){
      stat = stat + 1;
      delay(200);
    }
    else {
      digitalWrite(13, HIGH);
      delay(1000);
      digitalWrite(13, LOW);
      delay(1000);
    }
  }
}

void police(){ 
  int sound = analogRead(A5);
  if (stat%2 == 1){
    if (sound > 25){
      stat = stat + 1;
      delay(200);
    }
    else{
      digitalWrite(13, HIGH);
      delay(500);
      digitalWrite(13, LOW);
      digitalWrite(12, HIGH);
      delay(500);
      digitalWrite(12, LOW);
      delay(500);
    }
  }
}

Read the sound sensor each time through loop() and change the state when a sound is detected but do not use delay() anywhere as it blocks program execution during the delay() period.

See Using millis() for timing. A beginners guide, Several things at the same time and look at the BlinkWithoutDelay example in the IDE.

UKHeliBob:
Read the sound sensor each time through loop() and change the state when a sound is detected but do not use delay() anywhere as it blocks program execution during the delay() period.

Speaking of which, is there "standard" State Machine tutorial to which newbies should be pointed?

UKHeliBob:
Read the sound sensor each time through loop() and change the state when a sound is detected but do not use delay() anywhere as it blocks program execution during the delay() period.

See Using millis() for timing. A beginners guide, Several things at the same time and look at the BlinkWithoutDelay example in the IDE.

Thanks! It took some time before I understand how it worked but now it finally works!

gfvalvo:
Speaking of which, is there "standard" State Machine tutorial to which newbies should be pointed?

I'd be inclined to write one if you think there's enough interest.

Hold that thought and have a look here, State Machine and Timers, Medium level tutorial.

... another state machine link from arduino.cc's Uncle Mike (Grumpy_Mike).