Tips for Programming Constants on Your BeagleBone

By Rui Santos, Luis Miguel Costa Perestrelo

Constants are variables whose values never change throughout the program. They’re great ways to ensure that altering your script is fast and simple. An example in Python may help you get the idea.

The following example illustrates a (incomplete) snippet of code where the speed of several DC (direct current) motors — for an RC (remote control) car, for example — would be proportional to a constant value and the voltage read from some sensor.

motor1_speed = 5*voltage1
motor2_speed = 5*voltage2
motor3_speed = 5*voltage3
motor4_speed = 5*voltage4

When you test your remote-control car, find that you’re not satisfied with the results, and want to change the constant 5, you have no choice but to change it everywhere. You could change it just once if you define a constant like this:

SPEED_CONSTANT = 5
motor1_speed = SPEED_CONSTANT*voltage1
motor2_speed = SPEED_CONSTANT*voltage2
motor3_speed = SPEED_CONSTANT*voltage3
motor4_speed = SPEED_CONSTANT*voltage4

When you define a constant, testing for different values becomes much less tedious.

Constants are regular variables like any others, but they’re defined at the start and never changed through the program. To differentiate constants from other variables, type them in all caps.

You can also define a constant for a message that you’ll be printing many times and don’t want to type repeatedly, as in the following JavaScript script:

var SENSOR_MESSAGE = "The reading from your sensor is: "
(...)
console_output(SENSOR_MESSAGE + temperature_sensor)
console_output(SENSOR_MESSAGE + light_sensor)
console_output(SENSOR_MESSAGE + distance_sensor)

If you’ve programmed in languages such as C and C++ for example, you’ve probably dealt with constants in a similar fashion. From a computational point of view, those constants are quite different. For those languages, constants are their own data type; in fact, they’re simply replaced with their values everywhere before the code actually runs. In Python and BoneScript, though, from a technical point of view they’re regular variables like any others.