2

Arduino.h defines LOW as 0x0 and HIGH as 0x1. Does the Arduino API intend to expose that fact? Does it guarantee that this will always be that way?

In other words, what is the intended purpose of these manifest constants: LOW and HIGH?

  • Is this purely cosmetic mnemonics added as an alternative for 0/1 and false/true, for those who like LOW/HIGH better?

  • Or is this an attempt to abstract/isolate the user's source code from the actual representation of LOW and HIGH (e.g. in case the representation changes in the future)?

The underlying reason for this question is to figure out whether code like

digitalWrite(some_pin, true);
digitalWrite(some_other_pin, !digitalRead(some_other_pin));

is a good programming practice. (If LOW and HIGH are there to abstract the user's code form their actual values then code like that is definitely a bad programming practice.)

  • Couldn't it be both? – jose can u c Apr 26 at 18:49
  • @jose can u c: It could. But the truly critical part here is whether the answer to the second point is "yes". – AnT Apr 26 at 18:54
  • Looking at the precursor to Arduino framework, WConstants.h seems to have a commented out 0xFF as a potential definition of HIGH, so point 2 may be the case... – jose can u c Apr 26 at 19:12
4

The underlying reason for this question is to figure out whether code like

digitalWrite(some_pin, true);
digitalWrite(some_other_pin, !digitalRead(some_other_pin));

is a good programming practice. (If LOW and HIGH are there to abstract the user's code form their actual values then code like that is definitely a bad programming practice.)

Strictly speaking, no, that is not good programming practice.

digitalRead() returns an int. digitalWrite() expects an int. Using ! converts the int into a bool and then it's promoted back to an int again.

In fact, the "next gen" Arduino core API changes HIGH and LOW from a simple int to an enum - and that struggles with casting through bool like that:

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

You can see the problems that causes here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.