So, I'm using the Arduino Nano to develop a board. On this board I have a relay who it's switched by the Nano.
But during the execution of the code, I need to know the state of the output to make something. The usual fuction just to read the output last state would be the digitalRead(). But if I read the digital pin D9 (who it's connected to the relay driver) the fuction allways return 0 (false, off). If I read another digital pin, that fuction work normaly.
To get around the problem, I'm reading directly the PORT register. That isn't a problem, but I just whould like to know if someone has found this problem too.
digitalRead can be used but it is slow and unnecessary.
The code should control the relay, not the other way round as it's not an input device.
Here's one way to look at it:
byte relay_pin = 2;
bool relay_state = false;
// Turn on the relay
relay_state = true;
digitalWrite(relay_pin, relay_state ? HIGH : LOW);
// Turn off the relay
relay_state = false;
digitalWrite(relay_pin, relay_state ? HIGH : LOW);
if (relay_state) {
;// do something because you know the relay is on
} else {
;// or because you know it's off
}
As the previous responses demonstrate, it shouldn’t be necessary to read the output to know what it currently is.
I am curious, however, why this doesn’t work. I should say doesn’t work for the OP in this circumstance; I am as certain as I can be that I have used digitalRead on an output port w/o any problem.
I know I shoud use a firmware flag to have the state of an output.
My code it's for a test Jig and have more than 2000 lines of code. A several things run during the tests and in the last task i just wanna to double check the state output to apply a little delay.
It's quite of common to check the state of an output in programing just for redundancy, not for execute som important stufs.
My olny question was if somebody has faced the same isue with the digitalRead() fuction.