# When to read sensors whilst running a state machine?

**URL:** <https://forum.arduino.cc/t/when-to-read-sensors-whilst-running-a-state-machine/1411763>\
**Category:** Programming\
**Created:** [November 2, 2025, 3:59am UTC](https://forum.arduino.cc/t/when-to-read-sensors-whilst-running-a-state-machine/1411763 "2025-11-02T03:59:04Z")\
**Posts on this page:** 1\
**Showing post:** 14

<div class="post-metadata">

**Author:** ![J-M-L](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/j-m-l/32/766245_2.png) [@J-M-L](https://forum.arduino.cc/u/J-M-L)\
**Post date:** [November 3, 2025, 7:04am UTC](https://forum.arduino.cc/t/when-to-read-sensors-whilst-running-a-state-machine/1411763/14 "2025-11-03T07:04:17Z")

</div>

> [@renez](#):
>
> I’m now starting to wonder if a state machine is the right structure to go with?

It is definitely suitable.

If you don’t have a sensor to triggger an event because it’s just « wait for 5s in that state » - that’s OK. Timeout can be an event too.

Here is an example, typed here - untested

```arduino
enum State { WAITING_FOR_ACTIVATION, PROCESSING };
State currentState = WAITING_FOR_ACTIVATION;
constexpr byte sensorPin = 2;
unsigned long startTime = 0;

void stateMachine() {
  switch (currentState) {
    case WAITING_FOR_ACTIVATION:
      if (digitalRead(sensorPin) == LOW) {
        startTime = millis();
        Serial.println("Activated! Processing...");
        currentState = PROCESSING;
      }
      break;

    case PROCESSING:
      if (millis() - startTime >= 5000) {
        Serial.println("Processing done. Back to waiting.");
        currentState = WAITING_FOR_ACTIVATION;
      }
      break;
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(sensorPin, INPUT_PULLUP);
  Serial.println("Waiting for activation");
}

void loop() {
  stateMachine();
}

```

Here is a small introduction to the topic: [Yet another Finite State Machine introduction](https://forum.arduino.cc/t/yet-another-finite-state-machine-introduction/1198997)

---

_[View the full topic](https://forum.arduino.cc/t/when-to-read-sensors-whilst-running-a-state-machine/1411763)._
