# How to use state machine in loop function?

I am making a program with a state machine. im using pir sensor and led. here is one of the lines of code:
if (currentState == 2 || currentState == 3) processPirState(currentState);

it should call this function when current state is either 2 or 3:

void processPirState(int currentState)
{

if(currentState == 2)
{
if (pirStat == HIGH)
{
digitalWrite(ledPin, 1);
}
if (pirStat == LOW)
{
digitalWrite(ledPin, 0);
}
}

else if(currentState == 3)
{
digitalWrite(ledPin, 0);
}

}

however running the program and giving it 2 and 3 doesnt do anything in regards to the pir sensor. i feel like this is because it only gets called once as opposed to a loop, so it does indeed run but doesnt keep running therefore doesnt activate the pirsensor for more than 1 ms? please help, how would i go about solving this?

If you put your test and function call in loop() then it will be called each time through loop() if the condition is true. Is that not you want ?

Please post a complete sketch showing what you are doing and explaining how you want it to work

You could upgrade your sketch to a Finite State Machine that we are used to.
Tutorial: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/.
My own example: millis_and_finite_state_machine.ino

perhaps you meant

``````pirStat = digitalRead(pirPin);
``````

but why not simply

``````void
processPirState (
int currentState )
{
switch (currentState)  {
case 2:
break;

case 3:
digitalWrite (ledPin, 0);
break;
}
}
``````
``````void loop()
{
switch (currentState)
{
case 2:
pirStat = digitalRead(pirPin);  // note: fixed '==' error
digitalWrite(ledPin, pirStat);
break;

case 3:
digitalWrite(ledPin, LOW);
break;
}
}
``````

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.