Hello, can I do this or what's the right way to do it? Thank You
int power = 0; //Where to store the value
const int inPower = 4; //Pin on the Arduino
void setup(){
pinMode(inPower, INPUT);
}
void loop(){
int power = digitalRead(inPower);
if (power = HIGH){
//do something
}
}
DrAzzy:
or even - since HIGH is 1 (true) and LOW is 0 (false)
if (digitalRead(pin))
But the Arduino API for digitalRead() is defined as returning HIGH or LOW not 1 / 0 or true/false.
The specific values for HIGH and LOW are never specified and not guaranteed to be any particular values.
To make the assumption that HIGH is 1 and LOW is 0 or to the return value as a boolean return value is abusing the API.
Yes you can go look at the code and see that HIGH is 1 and LOW is 0 but the actual API never guarantees the values.
An implementer of that function is free to use any values and still conform to the API.
From a best practices programming point of view it is best to not abuse an API so the better choice would be
if (digitalRead(pin)==HIGH)
And if HIGH happens to be 1, it will generate the same compiled code as
if (digitalRead(pin))
which is not guaranteed to always work since the API offers no assurance that HIGH is a non zero value.
The specific values for HIGH and LOW are never specified and not guaranteed to be any particular values.
the values are well defined:
from arduino.h
#define HIGH 0x1
#define LOW 0x0
the return value from digitalRead is even an int, returning LOW or HIGH
from wiring_digital.c
int digitalRead(uint8_t pin)
[/quote]
so the function WILL return 1 or 0.
if someone decides to switch the definitions behind HIGH and LOW, these digitalRead comparisons will be the least problem...
You are looking at the internal implementation details of the underlying code.
Those values are not part of the actual documented API.
Using implementation details that are not part of an official API is abusing an API and goes against programming best practices.
While implementors of the digitalRead() function may choose to define HIGH as 1 and LOW as 0 they are not required to do so.
There are cases where it can make sense to abuse an API. Performance can be one of them.
However, when the choice to abuse an API is made, it should not be made lightly, and should be made with the understanding that it is possible that at some point in the future the code could break.