Jun-23-2020, 12:19 PM
Hey,
I want to write some program for a 4x4 button matrix, where it simply outputs the number of the button I press.
I'm using this code:
I've searched in other threads for solutions, but haven't found any that were fitting to my problem.
From these I only learned that you need to define functions, before you use them, but here that's clearly the case in my eyes. In fact, it's pretty much the first thing I did.
So I am a little baffled...
Any help is appreciated!
I want to write some program for a 4x4 button matrix, where it simply outputs the number of the button I press.
I'm using this code:
import time import RPi.GPIO as GPIO GPIO.setwarnings(True) class keypad(): def __init__(self, columnCount = 4): GPIO.setmode(GPIO.BCM) #Button settings if columnCount is 4: self.KEYPAD = [ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16] ] #RPI PIN-Allocation self.ROW = [18,23,24,25] self.COLUMN = [4,17,22,21] else: return def getKey(self): #Setting all columns as output for j in range(len(self.COLUMN)): GPIO.setup(self.COLUMN[j], GPIO.OUT) GPIO.output(self.COLUMN[j], GPIO.LOW) #Setting all rows as input for i in range(len(self.ROW)): GPIO.setup(self.ROW[i], GPIO.IN, pull_up_down=GPIO.PUD_UP) #Scanning rows for pressed buttons rowVal = -1 for i in range(len(self.ROW)): tmpRead = GPIO.input(self.ROW[i]) if tmpRead == 0: rowVal = i if rowVal < 0 or rowVal > 3: self.exit() return for j in range(len(self.COLUMN)): GPIO.setup(self.COLUMN[j], GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(self.ROW[rowVal], GPIO.OUT) GPIO.output(self.ROW[rowVal], GPIO.HIGH) colVal = -1 for j in range(len(self.COLUMN)): tmpRead = GPIO.input(self.COLUMN[j]) if tmpRead == 1: colVal = j if colVal < 0 or colVal > 3: self.exit() return #Returning the pressed button self.exit() return self.KEYPAD[rowVal][colVal] def exit(self): #Re-initializing all rows and columns for i in range(len(self.ROW)): GPIO.setup(self.ROW[i], GPIO.IN, pull_up_down = GPIO.PUD_UP) for j in range(len(self.COLUMN)): GPIO.setup(self.COLUMN[j], GPIO.IN, pull_up_down = GPIO.PUD_UP) if __name__ == '__main__': #Initializing the keypad kp = keypad() #Endless loop to check for pressed buttons while True: digit = None while digit == None: digit = kp.getKey() #Return of the button pressed print digit time.sleep(0.5)But when running it, I get the error:
Error:Traceback (most recent call last):
File "matrix.py", line 6, in <module>
class keypad():
File "matrix.py", line 71, in keypad
kp = keypad()
NameError: name 'keypad' is not defined
Apparently the main function doesn't know that keypad() doesn't exists...I've searched in other threads for solutions, but haven't found any that were fitting to my problem.
From these I only learned that you need to define functions, before you use them, but here that's clearly the case in my eyes. In fact, it's pretty much the first thing I did.
So I am a little baffled...
Any help is appreciated!