Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What variable type should I use to store an Arduino pin state?

Tags:

c++

arduino

The Arduino docs define the constants HIGH and LOW for digital I/O pins but don't specify what they are under the hood. So if I want to store a pin state in a variable, what type should the variable be? The logical assumption would be 1 and 0 in an int variable, or perhaps true and false in a bool, but I can't find this stated anywhere.

like image 750
Robert Lewis Avatar asked Oct 30 '25 00:10

Robert Lewis


1 Answers

From the documentation of digitalRead() (Which returns HIGH or LOW), the value is stored in an int, so using int seems like a safe bet.

The function digitalWrite() takes a pin status (HIGH or LOW) as a parameter, and searching through the GitHub repositories from Arduino for the definition of that function, there are three different definitions:

void digitalWrite(uint32_t, uint32_t);
void digitalWrite(uint8_t, uint8_t);
void digitalWrite(pin_size_t, PinStatus);

Where PinStatus is an enum:

typedef enum {
  LOW     = 0,
  HIGH    = 1,
  CHANGE  = 2,
  FALLING = 3,
  RISING  = 4,
} PinStatus;

But HIGH and LOW are always defined as 1 and 0, which can definitely be stored in an int (And can be converted to those three types)

like image 192
Artyer Avatar answered Oct 31 '25 13:10

Artyer