Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File not ready for write after open?

I have the following code:

#!/usr/bin/python

export = open('/sys/class/gpio/export', 'w')
export.write('44\n')

And this code produces the following output:

close failed in file object destructor:
IOError: [Errno 16] Device or resource busy

If I change the code by adding a export.close() to the end, I get this as output:

Traceback (most recent call last):
  File "./test.py", line 5, in <module>
    export.close()
IOError: [Errno 16] Device or resource busy

However, if I change the code again as such, it works perfectly:

#!/usr/bin/python
from time import sleep

export = open('/sys/class/gpio/export', 'w')
sleep(1)
export.write('44\n')

Note that .close ALWAYS fails, even if I put a long sleep after the write.

Edit:

Changed my code to be the following:

with open('/sys/class/gpio/export', 'w') as export:
    sleep(1)
    export.write('44\n')
    export.flush()
    export.close()

Still gives errors:

Traceback (most recent call last):
  File "./test.py", line 7, in <module>
    export.flush()
IOError: [Errno 16] Device or resource busy

Edit 2:

My main issue turned out to be that you can't export a GPIO that has already been exported. I've updated my code to look like this and it seems to be working:

from os import path

if not path.isdir('/sys/class/gpio/gpio44'):
    with open('/sys/class/gpio/export', 'w') as export:
        export.write('44\n')

if path.exists('/sys/class/gpio/gpio44/direction'):
    with open('/sys/class/gpio/gpio44/direction', 'w') as gpio44_dir:
        gpio44_dir.write('out\n')

if path.exists('/sys/class/gpio/gpio44/value'):
    with open('/sys/class/gpio/gpio44/value', 'w') as gpio44_val:
        gpio44_val.write('1\n')

This code successfully exports a GPIO, sets its direction to "out", and actives it (value to 1).

like image 903
Dave Avatar asked Mar 10 '26 03:03

Dave


1 Answers

My main issue turned out to be that you can't export a GPIO that has already been exported. I've updated my code to look like this and it seems to be working:

from os import path

if not path.isdir('/sys/class/gpio/gpio44'):
    with open('/sys/class/gpio/export', 'w') as export:
        export.write('44\n')

if path.exists('/sys/class/gpio/gpio44/direction'):
    with open('/sys/class/gpio/gpio44/direction', 'w') as gpio44_dir:
        gpio44_dir.write('out\n')

if path.exists('/sys/class/gpio/gpio44/value'):
    with open('/sys/class/gpio/gpio44/value', 'w') as gpio44_val:
        gpio44_val.write('1\n')

This code successfully exports a GPIO, sets its direction to "out", and actives it (value to 1).

like image 156
Dave Avatar answered Mar 12 '26 15:03

Dave