Take the 2-minute tour ×
Raspberry Pi Stack Exchange is a question and answer site for users and developers of hardware and software for Raspberry Pi. It's 100% free, no registration required.

I've made a program using the wiringPi library that assigns GPIO pins to toggle at the press of associated number keys. I'd like my program to show the current status of the pins, even if they are toggled by external means (like another user running the program over SSH). Is it "safe" to read the status of a pin set to output?

share|improve this question
add comment

1 Answer 1

up vote 4 down vote accepted

The answer

Yes it's safe. Judging from the source code of the library, it doesn't cache the values but reads them each time you call digitalRead function so it should work as expected.

Documentation

It isn't really documented in the wiringPi documentation but at least the documentation also doesn't say it's forbidden (for example for digitalWrite there is a not saying that you have to set the pin to OUTPUT first). So we have to dig deeper to get the answer.

Some background

WiringPi can control GPIO in two modes - using sysfs interface and using RaspberryPi specific registers in memory.

First option is a standard in Linux and it's documented here. Note that the documentation says:

However, note that not all platforms can read the value of output pins; those that can't should always return zero.

So we at least know that it is safe. I've checked by experimenting that it is supported on RaspberryPi.

This gives us a hint that reading output pin state is probably supported by the hardware itself but we can't be sure since it may be cached by the driver, for example. Lets check documentation:

The pin level registers return the actual value of the pin.

And it doesn't mention that it has to be set to OUTPUT. Experimentation seems to confirm this.

We can also check the [kernel driver] itself3:

lev = readl(gpio->base + GPIOLEV(gpio_bank))
return 0x1 & (lev >> gpio_field_offset);

So all it does is to indeed read the hardware register each time you read the state of the pin. And wiringPi does the same thing when not run in sysfs mode:

  if ((*(gpio + gpioToGPLEV [pin]) & (1 << (pin & 31))) != 0)
      return HIGH ;
  else
      return LOW ;
share|improve this answer
    
Great answer! Thanks! –  XAleXOwnZX Apr 11 '13 at 15:59
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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