Arduino programming guide series


Boolean arrays

It is a common practice to use arrays to store chars, ints, or double values.

But arrays can also store booleans. Here's how.

A boolean data-type is one that can take only two possible values. Usually these values are depicted as "TRUE" or "FALSE". You can also see them as "ON" or "OFF", or "1" or "0".

You may intuitively think that a boolean data-type can be stored with a single bit, instead of a full byte. Let's correct this right now: A boolean data type may be one of two possible values, but it still takes a full byte to store it in SRAM.

Still, even though boolean data-types will not save an SRAM, they are better suited than alternatives, like int or byte in many applications.

Let's look at an example.

Imagine that you have a set of dip switches connected to the digital pins of an Arduino.

Let's say that your dip switches are configured to produce the code "0101" in digital pins 3, 4, 5, 6.

You can capture this code and store it into a boolean array like this:

boolean dip_switch[4];
dip_switch[0] = digitalRead(3); // a boolean data type
dip_switch[1] = digitalRead(4); // a boolean data type
dip_switch[2] = digitalRead(5); // a boolean data type
dip_switch[3] = digitalRead(6); // a boolean data type

The configuration of the DIP switches is now stored in an array of type "boolean".

Boolean is a non-standard data type defines in the Arduino language, that is identical to the bool data type. In this example code, you could substitute "boolean" for "bool" without changing the outcome. In fact, the Arduino documentation recommends that you use "bool" instead of "boolean".

If you want to treat the dip_switch array as a half-byte word, then you can convert it to a decimal. You can do this with this code:

byte encodebool(boolean* arr)
  byte val = 0;
  for (int i = 0; i<4; i++)
    val << = = 1;
    if (arr[i]) val | = 1;
  return val;

If dip_switch contains "0,1,0,1", then encodebool(dip_switch) will return "5". 

With this simple example, you can use a DIP switch, store the positions of its switches to a boolean array, and convert the half-byte set on the DIP switch to a decimal on demand.

"Arduino programming" series

New to the Arduino?

Arduino Step by Step Getting Started is our most popular course for beginners.

This course is packed with high-quality video, mini-projects, and everything you need to learn Arduino from the ground up. We'll help you get started and at every step with top-notch instruction and our super-helpful course discussion space.