State machine example C code

This is example state machine code for the Race to the Wall. In this example, the pin configuration code is not shown. There are four states:

  1. Waiting for button to be pressed
  2. Waiting for button to be released
  3. Forward until wall is detected
  4. Reverse until white line

The state transitions are very straightforward. In most cases, each state simply leads to one other state. However, I have added multiple possible transitions in one state – on the return journey, the button can be pressed to start the robot going forwards again.

int main()
{
	int state = 1;
	int switch, colour;
	
	while (1)
	{
		// Read all sensors
		switch = PORTDbits.RD4;
		colour = read_analog_channel(0);
		
		// Choose state behaviour
		if (state == 1)
		{
			LATD = 0; // stop motor
			
			if (switch == 1) state = 2;
		}
		else if (state == 2)
		{
			LATD = 0; // stop motor
			
			if (switch == 0) state = 3;
		}
		else if (state == 3)
		{
			LATD = 0b01; // motor forwards
			
			if (switch == 1) state = 4;
		}
		else if (state == 4)
		{
			LATD = 0b10; // motor reverse
			
			if (colour < 512) state = 1;
			if (switch == 1) state = 2;
		}
	}
	
	return 0;
}
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s