Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python threading error, anyone got a solution?

I got a problem with my python program for my Raspberry Pi. I want to create a thread from a def in a class. It displays the following error when I try to run the code:

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)

Here is my code:

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

and:

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)

Anyone got a solution?

Thanks in advance

like image 552
JuNijland Avatar asked May 31 '26 23:05

JuNijland


1 Answers

You're doing it wrong. First of all:

def check_keys(self):

because it is a method of a class (the first parameter is always an instance). Secondly:

def __init__(self, gpio_col, gpio_row):
    COL = gpio_col
    ROW = gpio_row
    # some code

You either want to store those variables on the instance, in which case you should use self.COL = gpio_col (and then in check_keys refer to self.COL) or you want to change them globaly in which case you should use

def __init__(self, gpio_col, gpio_row):
    global COL
    COL = gpio_col

I advise storing them on the instance though.

Final note: you do realize that catching KeyboardInterrupt in a thread won't work because only the main thread can catch signals?

like image 148
freakish Avatar answered Jun 02 '26 20:06

freakish