Race to the Wall example code

I was glad to see today that the Race to the Wall has focused the minds of many teams on actually understanding the C code for their robot rather than just blindly copying and pasting something and hoping for the best. With that in mind, please read the following carefully and see if you can follow it:

//
// Race to the wall example code for MSP430G2553
// Written by Ted Burke – Last modified 28-10-2014
//
// This code assumes the following:
//
//   The switch is connected to P1.0 and goes high when pressed.
//   The colour sensor is connected to P1.1 and goes high on black.
//   Pins P2.0 and P2.1 are connected to the driver chip to control the motor.
//

#include <msp430.h>

int main(void)
{
    WDTCTL = WDTPW + WDTHOLD; // disable watchdog timer
    
    // set pins P2.0 and P2.1 as outputs to control motor
    P2DIR = 0b00000011;

    // while switch not pressed, drive motor forward
    while((P1IN & 0b00000001) == 0)
    {
        P2OUT = 0b00000001;
    }
    
    // while colour sensor low, drive motor in reverse
    while((P1IN & 0b00000010) == 0)
    {
        P2OUT = 0b00000010;
    }
    
    // stop motor forever
    while(1)
    {
        P2OUT = 0b00000000;
    }
    
    return 0;
}

Just for interest’s sake, here’s the exact same program boiled down to almost the bare minimum. I wouldn’t recommend writing the program this way since it’s difficult to read, but it’s interesting to reflect on how compact the “active ingredients” of the program actually are!

#include <msp430.h>
int main(void)
{
    WDTCTL = WDTPW + WDTHOLD;
    P2DIR = 0b00000011;
    while((P1IN & BIT0)==0) P2OUT=0b00000001;
    while((P1IN & BIT1)==0) P2OUT=0b00000010;
    while(1) P2OUT = 0b00000000;
    return 0;
}

The code above assumes a circuit similar to the following:

race_to_wall_example_circuit

[Download editable Inkscape SVG version of circuit diagram]

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