State machine example: Race to the Wall

//
// State Machine Example for MSP430G2553
// Written by Ted Burke, Last updated 19-11-2014
//

#include <msp430.h>

// main function
int main( void )
{
    // stop watchdog timer to prevent time out reset
    WDTCTL = WDTPW + WDTHOLD;
    
    // configure digital inputs and outputs
    P1DIR = 0b00000000; // P1.0-7 all digital inputs
    P2DIR = 0b00001111; // P1.0-1 left motor, P1.2-3 right motor

    // state variable
    int state = 1;
    
    // repeat the following steps indefinitely
    while(1)
    {
        // State 1: Pause before starting
        if (state == 1)
        {
            // both motors stop
            P2OUT = 0b00000000;
            
            // switch state after 2 seconds
            __delay_cycles(2000000); // 2 second delay
            state = 2;
        }
        
        // State 2: Forward to wall
        if (state == 2)
        {
            // both motors forwards
            P2OUT = 0b00001010;
            
            // switch state if switch pressed (P1.0 high)
            if ((P1IN & BIT0) == 1) state = 3;
        }
        
        // State 3: Reverse to black line
        if (state == 3)
        {
            // both motors reverse
            P2OUT = 0b00000101;
            
            // switch state if black line is detected (P1.1 high)
            if ((P1IN & BIT1) == 1) state = 4;
        }
        
        // State 4: Stop forever
        if (state == 4)
        {
            // both motors reverse
            P2OUT = 0b00000000;         
        }       
    }

    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