Program Flow and Control in brickOS

Robotics, unlike most basic programming tasks, is not a linear task. Robots usually have to perform a certain set of uninterrupted tasks repeatedly, while at the same time waiting for specific inputs from the outside world. This is difficult at best with similar linear programming, since you have to run a loop, check for something, and then fork, while still maintaining the original behavior in the new fork.

Basic thread and process control

Threading allows multiple processes to run side-by-side on the same chip. You get to learn (or have learned) all about this in CS167. If you haven't had threading experience yet, the TA staff highly recommends that you try and read through the CS167 lecture slides on threading.

#include <unistd.h>

Several things should be kept in mind when starting a thread with execi:

Don't forget to check out the command reference and the code samples page for more information on threading

Timing and Event Control

Three basic functions are used in brickOS to control time-related issues: sleep(), msleep(), and wait_event().

sleep(X) and msleep(X) do exactly what their names imply - they put a thread to sleep for an integral number of seconds or milliseconds X, respectively.

For more sophisticated waiting, there is wait_event(function_name, data). wait_event() allows you to create a function of type wakeup_t in your code, which should return a non-zero value when the condition you want to wait for (say, a button press) is satisfied, and zero otherwise.

This is one of the most important functions in the OS: you will want to use it (for example) to monitor bumpers, or check for button presses, or to activate the robot when light values change suddenly.

Check out the sample code page for an example of how to use wait_event

Semaphores

#include <semaphore.h>

Semaphores are sort of complex. For the students who haven't taken CS167, think of the word semaphore as another word for "lock". A program with multiple threads of control will often use semaphores (locks) to synchronize one thread with another (for example, a thread that controls the motors and a thread that takes light readings)

Most likely you will not be using semaphores. You are not required to understand them, but they are there if you want them. Once again, the cs167 lecture slides are recommended reading for understanding how semaphores work. brickOS semaphores are POSIX 1003.b compliant, so use them like you would most other semaphores.