11.16. InputMatcher1 Arduino Sketch

This sketch is used by Exercise: Input Pattern Matching.

11.16.1. Full Source Code

The full code is all in one file InputMatcher1.ino.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// InputMatcher1.ino : Arduino program to demonstrate a simple finite state machine program structure.

// Copyright (c) 2014, Garth Zeglin.  All rights reserved. Licensed under the terms
// of the BSD 3-clause license as included in LICENSE.

// The baud rate is the number of bits per second transmitted over the serial port.
const long BAUD_RATE = 115200;

// The state machine uses a single switch input.
const int INPUT_PIN = 4;

/****************************************************************/
/**** Standard entry points for Arduino system ******************/
/****************************************************************/

// Standard Arduino initialization function to configure the system.

void setup()
{
  // initialize the Serial port
  Serial.begin( BAUD_RATE );

  // configure our trivial inputs
  pinMode( INPUT_PIN, INPUT );
  pinMode( LED_BUILTIN, OUTPUT );
}

/****************************************************************/
// Standard Arduino polling function.

// This demonstrates the simplest method for representing a finite state machine
// as an Arduino program: the program counter is used to represent the current
// state as the current execution position with the program.  Note that a
// highly-connected state graph is not necessarily well represented by a
// hierarchical code structure, hence the use of goto, which is generally
// frowned upon in structured programming.

void loop()
{
  int input;

 start:
  Serial.println("Entering start state.");
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  Serial.println("Sampling input.");
  input = digitalRead( INPUT_PIN );
  if (input) goto state1;
  else goto start;

 state1:
  Serial.println("Entering state 1.");    
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  Serial.println("Sampling input.");
  input = digitalRead( INPUT_PIN );
  if (input) goto start;
  else goto state2;

 state2:
  Serial.println("Entering state 2.");    
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  Serial.println("Sampling input.");
  input = digitalRead( INPUT_PIN );
  if (input) goto state3;
  else goto state1;

 state3:
  Serial.println("Entering state 3.");
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  Serial.println("Sampling input.");
  input = digitalRead( INPUT_PIN );
  if (input) goto state3;
  else goto start;
}    

/****************************************************************/