How to use a boolean in Arduino? Answered


Author Options:

I need to learn how to use a boolean in arduino. How to set it to true or false, how  to read it, and an example of using a boolean to set a led on.




int LEDpin = 5; // LED on pin 5
int switchPin = 13; // momentary switch on 13, other side connected to ground

boolean running = false;

void setup()
pinMode(LEDpin, OUTPUT);
pinMode(switchPin, INPUT);
digitalWrite(switchPin, HIGH); // turn on pullup resistor

void loop()
if (digitalRead(switchPin) == LOW)
{ // switch is pressed - pullup keeps pin high normally
delay(100); // delay to debounce switch
running = !running; // toggle running variable
digitalWrite(LEDpin, running) // indicate via LED

I had tried that example but it didn't work, I need another one and a more specific example of how to set a Boolean true or false, and how to read it.

Then your wiring is wrong. That example works.

Boolean is a value just like an integer that can take a number, but instead of 0-65535 it can take a number 0 or 1.

That's it. You can compare a boolean to true, false, 1, 0, another integer, another boolean, or use the variable itself as a condition.

You can say things like
if (running) == TRUE;
if (running) == 1;
even just
if (running); // (works with boolean operators)

Personally, I've got VERY careful with those brackets.

I have this code but it isnt working and I dont know why, can you help me figure out the problem??

boolean mySet = false;
const int LED = 13;
const int BUTTON = 7;

void setup() {
pinMode(LED, OUTPUT);

void loop() {
if (BUTTON, HIGH) { // if switch is on
boolean (mySet == true); // set bolean to true
if (mySet == true) { // if boolean is true
digitalWrite(LED, HIGH); // the led will turn on

The syntax of your loop statement is all over the place. ;-)

You have confused the COMPARISON operator '==' with the ASSIGNMENT operator '=' The boolean values "true" and "false" are synonymous with "HIGH" and "LOW"

Your line boolean (mySet == true redefines mySet  Just because it compiles doesn't make it right. 'C' is a truly, truly horrible language.

Professionally, I avoid it like the plague and always write in Pascal or Delphi.


You have confused the PIN BUTTON, with the VALUE contained on that button, which is accessed with the digitalRead statement I have added.
boolean mySet = false;
constint LED = 13;
constint BUTTON = 7;
boolean myButton;

voidsetup() {
pinMode(LED, OUTPUT);

voidloop() {
if (myButton==true) mySet = true; // set bolean to true 

 digitalWrite(LED, mySet);

running=TRUE; //Watch the caps.

if (running==true) {digitalWrite(apin,FALSE);} //watch those caps.

All that is wrong is a missing semicolon as below

digitalWrite(LEDpin, running);

Good programme works well.