0
votes

Following on the discussion at State machine program design in FreeRTOS - vTaskStartScheduler in a switch statement, I have a state machine with 4 states, each of them with different tasks reading sensor data.

When a sensor data reaches a threshold, its task has to cause a state change.

The idea is to have a superior task which controls the states (and suspends/resumes corresponding tasks) with a switch statement. My question is: how should the sensor tasks communicate the STATE with the superior task?

One proposed solution is to have a set_state function which is called by the event generating task, but I read that having global variables in FreeRTOS is discouraged. I thought to implement it through Queues:

1- Task1 detects sensor threshold, and sends STATE to a Queue.

2- Superior task is blocked waiting to receive data from Queue. When it receives STATE, the switch statement processes the state change.

If this approach is correct, my doubt relates on how and where should be STATE defined (global, or just existing in the stack of each task, or the superior task...)

1

1 Answers

1
votes

STATE should exist only where it needs to, 'in' the superior task. I'm presuming you're using C, so declare STATE as a static variable in "superior_task.c" (or whatever it's called). This means it can then only be affected within that file - the C equivalent to a private member variable in C++.

Then, if your inferior tasks need to affect a state change, they post a state change event to a queue managed by the superior task. When the queue is processed, the superior state makes the change to the private STATE variable.

If other tasks need to know what the state is for their own processing, they can use an accessor for the private variable, e.g., State get_state() { return STATE; }. As Martin says though, the other tasks shouldn't need to know the state, as otherwise there's inter-dependencies between tasks that shouldn't exist.