尝试使用raspberry pi测试中断时出错

时间:2016-06-04 13:51:11

标签: python python-2.7 raspberry-pi raspberry-pi3

# Test interrupts.
import os
import select

write_once(os.path.join('/sys/class/gpio', 'export'), '22')

# Pin to work with
pin_base = '/sys/class/gpio/gpio22/'


def write_once(path, value):
   with open(path, 'w') as f:
      f.write(value)


f = open(os.path.join(pin_base, 'value'), 'r')

write_once(os.path.join(pin_base, 'direction'),
       'in')
write_once(os.path.join(pin_base, 'edge'),
       'falling')

po = select.poll()
po.register(f, select.POLLPRI)

while 1:
   events = po.poll(100)
   if not events:
      print ('timeout')
   else:
        f.seek(0)
        state_last = f.read()
        print 'Val: %s' % state_last
Traceback (most recent call last):
File "/home/pi/trigger.py", line 5, in <module>
write_once(os.path.join('/sys/class/gpio', 'export'), '22')
NameError: name 'write_once' is not defined

我试图使用write_once导出gpio 22并出现错误..有人可以提供帮助吗?

1 个答案:

答案 0 :(得分:0)

移动:

def write_once(path, value):
   with open(path, 'w') as f:
      f.write(value)

在第一次调用之前,直到文件的顶部。

语句按顺序执行,一次一个,因此您在定义之前调用它。或者,将您调用的调用放在另一个函数中write_once(),并确保在定义write_once()后调用该函数。

这是第一个建议:

# Test interrupts.
import os
import select


def write_once(path, value):
   with open(path, 'w') as f:
      f.write(value)

write_once(os.path.join('/sys/class/gpio', 'export'), '22')

# Pin to work with
pin_base = '/sys/class/gpio/gpio22/'

f = open(os.path.join(pin_base, 'value'), 'r')

write_once(os.path.join(pin_base, 'direction'), 'in')
write_once(os.path.join(pin_base, 'edge'), 'falling')

po = select.poll()
po.register(f, select.POLLPRI)

while True:
   events = po.poll(100)
   if not events:
      print ('timeout')
   else:
        f.seek(0)
        state_last = f.read()
        print 'Val: %s' % state_last

这是第二个:

# Test interrupts.
import os
import select


def run():
    write_once(os.path.join('/sys/class/gpio', 'export'), '22')

    # Pin to work with
    pin_base = '/sys/class/gpio/gpio22/'

    f = open(os.path.join(pin_base, 'value'), 'r')

    write_once(os.path.join(pin_base, 'direction'), 'in')
    write_once(os.path.join(pin_base, 'edge'), 'falling')

    po = select.poll()
    po.register(f, select.POLLPRI)

    while True:
       events = po.poll(100)
       if not events:
          print ('timeout')
       else:
            f.seek(0)
            state_last = f.read()
            print 'Val: %s' % state_last

def write_once(path, value):
   with open(path, 'w') as f:
      f.write(value)

run()

请注意,对于第二个示例,只要在调用run()之前定义了两个函数的顺序并不重要。