import RPi.GPIO as GPIO

 
class keypad():
    # kontakti a zadefinovanie pripojenia   
    KEYPAD = [
    [1,2,3,'A'],
    [4,5,6,'B'],
    [7,8,9,'C'],
    ['*',0,'@','D']
    ]
     
    ROW         = [7,11,13,15]
    COLUMN      = [12,16,18,22]
     
    def __init__(self):
        GPIO.setmode(GPIO.BCM)
     
    def getKey(self):
         
        # Nastavenie stlpcov ako výstup
        for j in range(len(self.COLUMN)):
            GPIO.setup(self.COLUMN[j], GPIO.OUT)
            GPIO.output(self.COLUMN[j], GPIO.LOW)
        
        # Nastavenie riadkov ako vstup
        for i in range(len(self.ROW)):
            GPIO.setup(self.ROW[i], GPIO.IN, pull_up_down=GPIO.PUD_UP)
        
        # Skenovanie riadkov
        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
        
        # Prevedenie stlpcov na vystup
        for j in range(len(self.COLUMN)):
                GPIO.setup(self.COLUMN[j], GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        
        # Prepnutie i-teho riadku sa nenašlo skenuje znova
        GPIO.setup(self.ROW[rowVal], GPIO.OUT)
        GPIO.output(self.ROW[rowVal], GPIO.HIGH)

        # Skenovanie stlpcov
        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 >2:
            self.exit()
            return

        # Vrati hodnotu po stlacení
        self.exit()
        return self.KEYPAD[rowVal][colVal]
        
    def exit(self):
        # Preinicializovanie všetkych riadkov a stlpcov
        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__':
    # Inicializuje triedu
    kp = keypad()
    
    # Vytvorenie smyčky čakania na klavesnicu
    digit = None
    while digit == None:
        digit = kp.getKey()
    
    # Vypis stlačenej klávesy do terminalu
    print digit 
