InputMatcher1 Arduino Sketch¶
This sketch is used by Exercise: Input Pattern Matching.
Full Source Code¶
The full code is all in one file InputMatcher1.ino.
1// InputMatcher1.ino : Arduino program to demonstrate a simple finite state machine program structure.
2
3// Copyright (c) 2014, Garth Zeglin. All rights reserved. Licensed under the terms
4// of the BSD 3-clause license as included in LICENSE.
5
6// The baud rate is the number of bits per second transmitted over the serial port.
7const long BAUD_RATE = 115200;
8
9// The state machine uses a single switch input.
10const int INPUT_PIN = 4;
11
12/****************************************************************/
13/**** Standard entry points for Arduino system ******************/
14/****************************************************************/
15
16// Standard Arduino initialization function to configure the system.
17
18void setup()
19{
20 // initialize the Serial port
21 Serial.begin( BAUD_RATE );
22
23 // configure our trivial inputs
24 pinMode( INPUT_PIN, INPUT );
25 pinMode( LED_BUILTIN, OUTPUT );
26}
27
28/****************************************************************/
29// Standard Arduino polling function.
30
31// This demonstrates the simplest method for representing a finite state machine
32// as an Arduino program: the program counter is used to represent the current
33// state as the current execution position with the program. Note that a
34// highly-connected state graph is not necessarily well represented by a
35// hierarchical code structure, hence the use of goto, which is generally
36// frowned upon in structured programming.
37
38void loop()
39{
40 int input;
41
42 start:
43 Serial.println("Entering start state.");
44 digitalWrite(LED_BUILTIN, LOW);
45 delay(1000);
46 Serial.println("Sampling input.");
47 input = digitalRead( INPUT_PIN );
48 if (input) goto state1;
49 else goto start;
50
51 state1:
52 Serial.println("Entering state 1.");
53 digitalWrite(LED_BUILTIN, LOW);
54 delay(1000);
55 Serial.println("Sampling input.");
56 input = digitalRead( INPUT_PIN );
57 if (input) goto start;
58 else goto state2;
59
60 state2:
61 Serial.println("Entering state 2.");
62 digitalWrite(LED_BUILTIN, LOW);
63 delay(1000);
64 Serial.println("Sampling input.");
65 input = digitalRead( INPUT_PIN );
66 if (input) goto state3;
67 else goto state1;
68
69 state3:
70 Serial.println("Entering state 3.");
71 digitalWrite(LED_BUILTIN, HIGH);
72 delay(1000);
73 Serial.println("Sampling input.");
74 input = digitalRead( INPUT_PIN );
75 if (input) goto state3;
76 else goto start;
77}
78
79/****************************************************************/