pad.mattdiesel.co.uk

Snippet - FSM Implementation C++

FSM Implementation C++ (C++)


Created 2015-02-20 15:28:22.594750 by Matt.

 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
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>

class fsmOne
{
private:
	int _state;
public:
	fsmOne() : _state(0) {}
	~fsmOne() {}
	
	void loop() {

		std::cout << "S1." << _state << std::endl;

		switch (_state) {
			case 0:
				_state = 1;
				break;

			case 1:
				_state = 5;
				break;

			case 5:
				break;
		}

		return;
	}

	void reset() { _state = 0; }

	bool end() const {
		return( _state == 5 );
	}
};




class fsmTwo
{
private:
	fsmOne one;
	int _state;
public:
	fsmTwo() : _state(0) {}
	~fsmTwo() {}
	
	void loop() {

		std::cout << "S2." << _state << std::endl;

		switch (_state) {
			case 0:
				_state = 1;
				one.reset();
				break;

			case 1:
				one.loop();
				if (one.end()) {
					_state = 5;
				}
				break;

			case 5:
				break;
		}

		return;
	}

	void reset() { _state = 0; }

	bool end() const {
		return( _state == 5 );
	}
};


int main(int argc, char const *argv[])
{
	fsmTwo two;

	do {
		two.loop();
	} while (!two.end());

	return 0;
}