I am trying to read the value of an output pin. online forums say that digitalRead(pinNum);
should work, but that is not the case here. digitalRead always returns 0 (LOW).
This is the code:
int pin = 22; // or 13, or 3 ...
void setup()
{
Serial.begin(9600);
pinMode(pin,OUTPUT);
}
void loop()
{
digitalWrite(pin,HIGH);
delay(100);
Serial.println(digitalRead(pin));
delay(100);
digitalWrite(pin,LOW);
delay(100);
Serial.println(digitalRead(pin));
delay(100);
}
printed values:
0
0
0
...
4 Answers 4
That method only works on AVR based systems. It exploits a "feature" whereby the IO pin, when in OUTPUT mode, is also in INPUT mode at the same time, and reading the pin reads the value that the pin is being driven to by the digitalWrite function.
The same is not true of the Due, which is an ARM based system. The IO pins function completely differently and the same "feature" cannot be used.
You will have to remember the state of the pin yourself.
Majenko's answer basically explains the cause - apparently on the SAM3X8E reading the input data register will not show the state being driven on output lines in the way it would on some other devices like the AVR.
However the conclusion that "you will have to remember the state of the pin yourself" is not correct.
According to the data sheet, the output data state can be read from the relevant port's PIO_ODSR
register. That the Arduino libraries don't do this could be an oversight, but probably is an efficiency decision, as they would need to examine the direction of each pin to determine the register to read for its state.
It would not be hard to make your own functions or macros to read the PIO_ODSR
- you could model them on the digitalInput()
ones.
try editing...
Serial.println(digitalRead(pin));
to .....
Serial.println(digitalRead(pin), DEC);
This works on my arduino Leonardo.
-
1No. The actual issue has already been explained. This question is about a Due and arrises from differences between that and more classic AVR Arduinos.Chris Stratton– Chris Stratton2016年10月03日 14:51:41 +00:00Commented Oct 3, 2016 at 14:51
Feed the output to a (spare) input pin and digitalRead()
that pin!
-
1Actually the output data can be read in software, it just needs to be read from a different register than the input data.Chris Stratton– Chris Stratton2016年04月29日 18:39:57 +00:00Commented Apr 29, 2016 at 18:39