If a digitalRead returns a boolean 'LOW' value is that 'LOW' value able to be transferred as 'LOW' or does it become a numeric '0' value? Will 'relay_state' be interpreted as 'LOW' or '0' in the code below?
cpp
int debounceDelay = 50;
current_relay_input = digitalRead(relay);
if (current_relay_input != previous_relay_input) {
RelayLastDebounceTime = current_Millis;
}
if (current_Millis - RelayLastDebounceTime > debounceDelay) {
relay_state = current_relay_input;
previous_relay_input = current_relay_input;
}
if (relay_state == LOW) { // should I check for LOW or '0'?
Serial.print(" do something....");
}
int digitalRead(uint8_t pin)
{
uint8_t timer = digitalPinToTimer(pin);
uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);
if (port == NOT_A_PIN) return LOW;
// If the pin that support PWM output, we need to turn it off
// before getting a digital reading.
if (timer != NOT_ON_TIMER) turnOffPWM(timer);
if (*portInputRegister(port) & bit) return HIGH;
return LOW;
}
And LOW and HIGH are defined in Arduino.h
#define HIGH 0x1
#define LOW 0x0
From the megaAVR core (Nano Evevry and Uno WiFi Rev2)
PinStatus digitalRead(uint8_t pin)
{
/* Get bit mask and check valid pin */
uint8_t bit_mask = digitalPinToBitMask(pin);
if(bit_mask == NOT_A_PIN || isDoubleBondedActive(pin)) return LOW;
// If the pin that support PWM output, we need to turn it off
// before getting a digital reading.
turnOffPWM(pin);
/* Get port and check valid port */
PORT_t *port = digitalPinToPortStruct(pin);
/* Read pin value from PORTx.IN register */
if(port->IN & bit_mask){
return HIGH;
} else {
return LOW;
}
return LOW;
}
I like this approach as it enables me to pass a "true" or "false" value instead of trying to know with certainty what 'LOW' represents. All of this was precipitated by trying to employ debounce code for some digital inputs where the relat contacts were 'bouncing' on the physical change of state. I was picking it up in the array structure where I could see the fast change of state being recorded.
But the debounce code seemed to be misinterpreting the 'LOW' value. At any rate going with your suggestion should clean things up.
which makes for readable code, and one place to change how you wired your switches should it come to that.
There is an equivalent set of things to know and keep in mind around digitalWrite(), which again technically should only be passed LOW or HIGH for the value to put on the pin.
My code is so convoluted it is embarrassing talking with those who write on a pro level. But the good thing is as I learn more I am able to go back and rewrite the stuff that is unreadable. If it works logically great but if you have to come back six months later and do something else it really helps if it is in a presentable form. Probably 50% of my code would be considered superfluous/unnecessary by anyone with a high level of programming skills. ...lol...