我的Raspberry Pi的python程序出了问题。我想从类中的def创建一个线程。我尝试运行代码时显示以下错误:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 505, in run
self.__target(*self.__args, **self.__kwargs)
TypeError: check_keys() takes no arguments (1 given)
这是我的代码:
import thread
import RPi.GPIO as GPIO
import threading
ROW = []
COL = []
chars = []
GPIO.setmode(GPIO.BOARD)
MATRIX = [ ['1','2','3'],
['4','5','6'],
['7','8','9'],
['*','0','#'] ]
class keypad():
def __init__(self, gpio_col, gpio_row):
COL = gpio_col
ROW = gpio_row
for j in range(3):
GPIO.setup(COL[j], GPIO.OUT)
GPIO.output(COL[j], 1)
for i in range(4):
GPIO.setup(ROW[i], GPIO.IN, pull_up_down = GPIO.PUD_UP)
def check_keys():
try:
while(True):
for j in range(3):
GPIO.output(COL[j],0)
for i in range(4):
if GPIO.input(ROW[i]) == 0:
chars.append(MATRIX[i][j])
print(MATRIX[i][j])
while(GPIO.input(ROW[i]) == 0):
pass
GPIO.output(COL[j],1)
except KeyboardInterrupt:
GPIO.cleanup()
def get_chars():
return chars
和
import socket
import time
import pylcdlib
import keypadlib
from threading import Thread
#init keypad
ROW = [23,21,19,18]
COL = [13, 15, 16]
keypad = keypadlib.keypad(COL, ROW)
thread = Thread(target = keypad.check_keys)
有人有解决方案吗?
提前致谢
答案 0 :(得分:2)
你做错了。首先:
def check_keys(self):
因为它是类的方法(第一个参数始终是实例)。其次:
def __init__(self, gpio_col, gpio_row):
COL = gpio_col
ROW = gpio_row
# some code
您要么想要在实例上存储这些变量,在这种情况下您应该使用self.COL = gpio_col
(然后在check_keys
中引用self.COL
)或者您想要在全局中更改它们你应该使用哪种情况
def __init__(self, gpio_col, gpio_row):
global COL
COL = gpio_col
我建议将它们存储在实例上。
最后注意:你确实意识到在线程中捕获KeyboardInterrupt
是行不通的,因为只有主线程可以捕获信号?