void move_forward(); // Moves forward one unit void turn_left(); // Turns 90 degrees to the left int detect_wall(); // Is there a wall in front of us?Then to move forward four times to a wall we know about, we can tell the computer
int main() {
move_forward();
move_forward();
move_forward();
move_forward();
}
This explains to the computer that the main function should simply
call the move_forward function four times. Using functions makes each
explination simpler. You don't actually have to describe how to
move forward each time, only that you want it done.
What happens if the wall is further down?
void move_to_a_wall() {
while (!detect_wall())
move_forward();
}
This will check for a wall each time before moving. A computer isn't very
smart, and needs it spelled out that it needs to keep looking. This program
literally translates to:
"Keep moving forward, but before each step, check that you have not found a wall"
Notation like "!" for "not" is common in C, just to keep things short and sweet.
void follow_circular_track() {
// while TRUE is true, keep going. That is to say, never stop :)
while (TRUE) {
move_to_a_wall();
turn_left();
}
}
This uses the move_to_a_wall function we made earlier. It moves forward until it finds a wall, then turns left. Since this continues forever, it should just keep running around the room it's in, anticlockwise. You can see how things which you've alreday explained to the computer don't need to be explained again. You can also see the use of "{" and "}" pairs to bracket a few instructions in to a single one.
void another_follow_circular_track() {
if (detect_wall() || FEELS_LIKE_IT) {
turn_left(); // turn around first
turn_left(); // just to show off :)
follow_circular_track();
} else {
follow_circular_track();
}
}
This will run around the inside of a circular track, like the
previous function. The difference is that it's already facing a wall, or
if it feels like it, the robot will do an about turn before starting the run.
"||" is C for "or", while "&&" is C for
"and".
void turn_right() {
int i;
for (i=0; i<3; i++)
turn_left();
}
This introduces the last few points to my talk. To turn right, you can simply turn left three times. Instead of typing it out three times, however, it's easy to get the computer to count to three for you. Don't worry too much about the details unless you're interested. It's an unusual implementation that allows this counting loop to behave more like a while loop.
Variables are a vital part of programming. They are how a computer keeps track of things, like the counting above. "i" is a whole number, which is used for counting to three. They can get quite complex at times, mirroring the complexity of the problem they try to solve, so it's best to consult a book, or myself to learn more about them.
Special thanks to aj for writing the library used for demonstrations during the talk.