513
edits
No edit summary |
|||
Line 89: | Line 89: | ||
The final missing part is the off-button. | The final missing part is the off-button. | ||
— BILD — | — BILD — | ||
==Writing the Program== | |||
Translating our diagram into a functional program is a relatively simple task. | |||
Step 1: saving the current state into a variable | |||
First of all we need a variable that saves the current state. It represents our State Machines memory. | |||
The most suitable type for such a variable is in this case an „[https://en.wikipedia.org/wiki/Enumerated_type enum]“. | |||
This enum assigns different names to values: | |||
––BILD–– | |||
Note (enum + Processing): the definition of an enum has to be saved in a separate file (tab) with an .java extension. ([http://stackoverflow.com/questions/13370090/enums-in-processing-2-0 more info] ) | |||
Step 2: choosing alternative actions | |||
Now we need something that executes different code depending on the current state. | |||
For this purpose we will have a closer look at the [https://www.arduino.cc/en/Reference/SwitchCase switch/case] statement. | |||
It operates similar to an if-condition whereas it can choose from more than two (if… else..) alternatives. | |||
It could for instance run over and over again in the main loop-function of our program: | |||
––BILD–– | |||
Step 3: defining the practical behavior of each state | |||
From now on it makes sense to use functions (aggregation of code) in order to keep a clean overview of our program. | |||
Each function includes the particular code that defines the behavior of a certain state. | |||
The internal structure of these functions is always the same: | |||
1) conduct actions that fit to the particular state. (turn motors on / off, start a timer, ..) | |||
2) read input data (sensors, timer, ..) that provides information about the next possible state | |||
3) decide the next state | |||
The third part can be done quite comfortably by giving back the new „state“ - value in form of the functions „return“ - value into the main loop. | |||
This is an example of how the „standy“-state could look like: | |||
––BILD–– | |||
Step 4: assembling everything | |||
We can now call each particular function in the appropriate part of the switch/case statement. | |||
The functions return value is saved in the state variable for the next loop. | |||
Step 5: extending the program | |||
This kind of program structure can easily be extended by additional states without disturbing the overall clarity. | |||
Therefore it makes sense to begin with a simple structure and to then add functions that are more complex. |
edits