测试python 2.7 / RaspberryPi上的wiringPi2中断,似乎无法使其工作。
使用以下代码,中断会生成分段错误。
#!/usr/bin/env python2
import wiringpi2
import time
def my_int():
print('Interrupt')
wpi = wiringpi2.GPIO(wiringpi2.GPIO.WPI_MODE_PINS)
wpi.pullUpDnControl(4,wpi.PUD_UP)
wpi.wiringPiISR(4, wpi.INT_EDGE_BOTH, my_int())
while True:
time.sleep(1)
print('Waiting...')
Waiting...
Waiting...
Waiting...
Waiting...
Segmentation fault
如果我在没有“()”的情况下回调,那么我会收到另一个错误:
wpi.wiringPiISR(4, wpi.INT_EDGE_BOTH, my_int)
> TypeError: in method 'wiringPiISR', argument 3 of type 'void (*)(void)'
我做错了什么???
答案 0 :(得分:3)
我对C不太好,但就我从源https://github.com/Gadgetoid/WiringPi2-Python/blob/master/wiringpi_wrap.c所理解的那样,你因为这段代码而得到了这个错误(它检查函数是否返回void并显示错误):
int res = SWIG_ConvertFunctionPtr(obj2, (void**)(&arg3), SWIGTYPE_p_f_void__void);
if (!SWIG_IsOK(res)) {
SWIG_exception_fail(SWIG_ArgError(res), "in method '" "wiringPiISR" "', argument " "3"" of type '" "void (*)(void)""'");
}
因此,我建议明确地在my_int()函数中返回True
或1。现在,对于已经到达函数代码末尾但没有返回任何值的函数,python返回None。
修改后的代码:
#!/usr/bin/env python2
import wiringpi2
import time
def my_int():
print('Interrupt')
return True
# setup
wiringpi2.wiringPiSetupGpio()
# set up pin 4 as input
wiringpi2.pinMode(4, 0)
# enable pull up down for pin 4
wiringpi2.pullUpDnControl(4, 1)
# attaching function to interrupt
wiringpi2.wiringPiISR(4, wiringpi2.INT_EDGE_BOTH, my_int)
while True:
time.sleep(1)
print('Waiting...')
编辑:您似乎错误地初始化了wirespi2。请查看教程以获取详细信息:http://raspi.tv/2013/how-to-use-wiringpi2-for-python-on-the-raspberry-pi-in-raspbian