我有以下代码:
#!/usr/bin/python export = open('/sys/class/gpio/export', 'w') export.write('44\n')
而这段代码产生以下输出:
close failed in file object destructor: IOError: [Errno 16] Device or resource busy
如果我通过在最后添加一个export.close()来更改代码,我将它作为输出:
Traceback (most recent call last): File "./test.py", line 5, in <module> export.close() IOError: [Errno 16] Device or resource busy
但是,如果我再次更改代码,则完美:
#!/usr/bin/python from time import sleep export = open('/sys/class/gpio/export', 'w') sleep(1) export.write('44\n')
请注意。即使我在写入后进行了长时间的睡眠,总是失败。
编辑:
将我的代码更改为以下内容:
with open('/sys/class/gpio/export', 'w') as export: sleep(1) export.write('44\n') export.flush() export.close()
仍然给错误:
Traceback (most recent call last): File "./test.py", line 7, in <module> export.flush() IOError: [Errno 16] Device or resource busy
编辑2:
我的主要问题是你不能导出已经导出的GPIO。 我已经更新我的代码看起来像这样,它似乎工作:
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')
此代码成功导出GPIO,将其方向设置为“out”,并将其激活(值为1)。
我的主要问题是你不能导出已经导出的GPIO。 我已经更新我的代码看起来像这样,它似乎工作:
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')
此代码成功导出GPIO,将其方向设置为“out”,并将其激活(值为1)。