cpjfox:
Ahhhh, so the chip counts the number of states and it applies a number to each one for you?
No. You have to write your own bugs. Don't worry, you're doing fine there.
![]()
But you are on the way to working code.
if (mySwitch.available()) {
unsigned long value = mySwitch.getReceivedValue();
switch (getReceivedValue()) {
Here you put the received value into a variable named 'value', but instead of using that result for switch-case you ....
well are you trying to use what you stored in 'value' or are you trying to read that switch -again-?
If the former then switch (value) would be more right.
If the latter then think again; you got the data that was available and would need to check if more data is available before getting it --- but why collect twice to make one decision? That makes no sense in this case. I think you got tired/confused even before you wrote that.
A state machine is a way to write code that may behave differently each time around depending on a value in a variable that your code sets.
Like if my code is looking at serial data for numbers and turn those into ints, I might set state to zero when no number is yet found and then to one when it has found a digit or more in a row then back to zero when the number is complete.
The code is then reduced checking on data available and if so then to one of two different actions:
During state zero my code is looking for that first digit. When it finds a digit, it sets an int to equal that value and sets the state to one. If not a digit then state stays zero.
During state one if any non-digit is found the state is set to zero and the int value is used for whatever it is for. If another digit is found then the int value is multiplied by ten and the new digit is added, but state does not change.
You see how simple the control is? State either changes or it doesn't. That is the control.
State can mean anything you want and be much more complex than above. I usually include an error state if -anything- unexpected/unwanted can happen. Then maybe I print an error and... set state to zero.
A state machine can save you from needing a mess of nested loops and logic that make debugging a real PITA.