Search code examples
linuxcommand-linegpiosysfs

set/reset GPIO though command line is not working as expected


I am trying to set/reset the GPIO value through sysfs. I took this document as reference.

At one point I am little confused, the scenario is given below

exported gpio 200 to test

mx6q:/sys/class/gpio/gpio200# echo "out" > direction   <-- set the direction as write(out)
mx6q:/sys/class/gpio/gpio200# cat direction            < -- just to verify
out
mx6q:/sys/class/gpio/gpio200# echo 1 > value           < -- set value as 1(high)
mx6q:/sys/class/gpio/gpio200# cat value                
1
mx6q:/sys/class/gpio/gpio200# echo 0 > value           < -- set value Low again
mx6q:/sys/class/gpio/gpio200# cat value
0
mx6q:/sys/class/gpio/gpio200# cat direction
out
mx6q:/sys/class/gpio/gpio200# echo "in" > direction      < -- change the direction to read the pin
mx6q:/sys/class/gpio/gpio200# cat direction
in
mx6q:/sys/class/gpio/gpio200# cat value                 < -- what i am expecting here is 0 (last set value)  
1

So regardless the value i Set before , i am always reading a high value. is this really expected behavior? I am confused at two points,

  1. why the previously set value is not persisting after i change the direction?
  2. what does the "Direction" really means, if i can cat for the value in both "in" and "out" case?

Please suggest a proper document to read to get a clear idea about GPIO operations. Thanks in advance


Solution

  • what does the "Direction" really means, if i can cat for the value in both "in" and "out" case?

    This question is a little unclear, but maybe this helps:

    If direction is out, then the data in value defines the logic level you want to set on the GPIO pin.

    If the direction is in, then the data in value is the logical level currently being read from the GPIO pin.

    why the previously set value is not persisting after i change the direction?

    Imagine that you have the pin tied to ground.

    If you set direction to out and write 1 to value, then of course when you read back value you will see 1 because that's what you just requested.

    If you were then set to set direction to in, value would now read 0 because you have the pin tied to ground, so you are currently reading a logical 0 from the pin.