5

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

7

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.

1
  • 1
    I cannot upvote yet, but thank you!
    – Makan
    Commented Jul 20, 2015 at 14:50
1

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.

1

try editing...

Serial.println(digitalRead(pin));

to .....

Serial.println(digitalRead(pin), DEC);

This works on my arduino Leonardo.

1
  • 1
    No. The actual issue has already been explained. This question is about a Due and arrises from differences between that and more classic AVR Arduinos. Commented Oct 3, 2016 at 14:51
0

Feed the output to a (spare) input pin and digitalRead() that pin!

1
  • 1
    Actually the output data can be read in software, it just needs to be read from a different register than the input data. Commented Apr 29, 2016 at 18:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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