I am trying to insert data into a mysql database with a keypad connected to a Rasperry PI using python.
The code:
#!/usr/bin/python
import os
import MySQLdb
import RPi.GPIO as GPIO
import time
#Open db conn
db = MySQLdb.connect("remote_server.com","user","password","database")
# prep cursor
cursor = db.cursor()
GPIO.setmode(GPIO.BOARD)
MATRIX = [ [1,2,3],
[4,5,6],
[7,8,9],
['*',0,'#'] ]
ROW = [7,11,13,15]
COL = [23,21,19]
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)
try:
while(True):
for j in range(3):
GPIO.output(COL[j],0)
for i in range(4):
if GPIO.input(ROW[i]) == 0:
mysql_code = MATRIX[i][j]
print mysql_code
try:
cursor.execute('''Insert into Rasperry_Codes (Code, insertTS) VALUES (%s, NOW())''', (mysql_code))
except MySQLdb.Error, e:
try:
print "MySQL Error [%d]: %s" % (e.args[0], e.args[1])
except IndexError:
print "MySQL Error: %s" % str(e)
db.commit()
time.sleep(0.2)
while(GPIO.input(ROW[i]) == 0):
pass
GPIO.output(COL[j],1)
except KeyboardInterrupt:
GPIO.cleanup()
Sometimes the data is inserted into database, sometimes not.
No error is given from mysql MySQLdb.Error.
print mysql_code
always prints the correct pressed number.
Does anybody see a problem that could cause that random malfunction?