Home / Codes / Using Arduino Struct

Using Arduino Struct

Structs (short for structure) are far less common in Arduino programming because they are mostly used in C whereas Arduino is based on C++. However, they are still a very useful tool especially if there is a need for user-defined data set. This tutorial aims to help you understand how to use Arduino structs.

Introduction

When you have multiple instances of a variable with the same data type, you normally use an array. For example:

Here, we have an array of size 10, all composed of integers.

Now what if we want to have a group of variables but of different data types? This is where structs are very useful.

For simplicity, let me start off with a basic example and then we’ll apply structs to Arduino programming.

 

Defining a Struct

Let’s create a struct for a ball. The ball struct contains two data types, a string(as char pointer) and a double. The string data type is the ball’s color while the double data type is its radius.

Now if we want to define a ball, we just do it like this:

Members of a struct is accessed using the dot (.) operator.

We could also use the typedef modifier to make struct declarations shorter:

With typedef, declaring a struct will now be:

One good advantage of using structs is when passing multiple variables to a function. Let’s say you have a function that accepts a string and a double as parameters:

By using structs, one parameter will now be passed instead of two:

Brackets can also be used to give values to the members of a struct. The above example is the same as the one below:

Using Structs in Arduino Programming

Now let’s apply structs in an Arduino sketch. For this example, we’ll use an RGB LED with Arduino. If you read the article on the link, you’ll know that an RGB LED has four terminals. We will follow this connection:

arduino RGB LED wiring common cathode

Normally, we will use this sketch to display the color red:

Here, the RGB LED pins are connected to digital pins 6, 5 and 3 as shown in the wiring diagram and on this part of the sketch:
The red color is displayed because the “r” pin receives the maximum pulse width while the other pins have no pulse:
If we are to modify this sketch by adding structs, the first thing to do is define a struct like this:
Here, the struct contains three integer elements named after the basic colors. Next, we define a function that accepts three integers as parameters and sends pulses to the RGB LED based on the passed parameters.
But since we are using Arduino struct, we don’t need to pass three parameters. All we have to do is give values to the members of the struct and pass that struct to the function. For example, to set the RGB LED’s color to red:
Here is now the full sketch:

Leave a Reply

Your email address will not be published. Required fields are marked *