Python 如何将raspberer pi 3火焰传感器火灾探测数据插入MySQL数据库
我想将raspberry pi 3中的数据插入mysql数据库:Python 如何将raspberer pi 3火焰传感器火灾探测数据插入MySQL数据库,python,mysql,raspberry-pi,Python,Mysql,Raspberry Pi,我想将raspberry pi 3中的数据插入mysql数据库: import RPi.GPIO as GPIO import time import MySQLdb db =MySQLdb.connect(host="localhost", user="root", passwd="123456", db="raspbd") cur = db.cursor() GPIO SETUP channel = 3 GPIO.setmode(GPIO.BCM)GPIO.setup(channel,
import RPi.GPIO as GPIO import time import MySQLdb db =MySQLdb.connect(host="localhost", user="root", passwd="123456", db="raspbd") cur = db.cursor()
GPIO SETUP
channel = 3 GPIO.setmode(GPIO.BCM)GPIO.setup(channel, GPIO.IN)def callback(channel):print("flamedetected")GPIO.add_event_detect(channel,GPIO.BOTH, bouncetime=300) # let us know when the pin goes HIGH or LOW GPIO.add_event_callback(channel, callback) # assign function to GPIO PIN,Run function on change
infinite loop
while True:cur.execute("INSERT INTO flame (ID,flame,) VALUES (%s, %s)", [ID,flame])db.commit() db.rollback()time.sleep (1)cur.close()db.close()
错误消息:
ERROR: Traceback (most recent call last):
File "flame.py", line 24, in cur.execute("INSERT INTO flame (ID,flame,) VALUES (%s, %s)", [ID,flame])
NameError: name 'ID' is not defined
在我看来,你应该避免使用无限循环,这是你应该避免的 错误消息表示名为ID的变量尚未定义,这意味着它不存在,因此也没有值。 我假设这应该是MySQL DB表中的ID,您最好将其设置为自动递增,这样就不用担心了 如果这就是您共享的全部代码,那么您很可能会收到更多的错误消息。您需要先从GPIO读取数据,才能将其发送到DB 直接回答如何从传感器获取数据到数据库。我根本没有GPIO的经验。这是一个记录良好的RPi领域 首先,您需要从相关pin/通道读取数据,然后通过SQL查询将其发送到DB gpiowiki()非常详细地描述了如何进行阅读。我假设您试图通过在管脚上附加回调函数来实现线程化解决方案,该函数将在每次传感器向管脚发送信号时触发。我不确定这样做是否正确:
# ...after setting up the GPIO and the DB connection
flame = ""
def my_callback(channel):
# ...do something here...
flame = GPIO.input(channel)
# or perhaps you want just a string when it happened
# flame = "detected"
channel = 3
GPIO.add_event_detect(channel, GPIO.RISING, callback=my_callback)
# then you should be able to write the value to the DB
cur.execute("INSERT INTO flame (ID,flame) VALUES (%s,%s)",[ID,flame])
# ...and continue with the DB job.
# please note that this piece of code is not complete
# and will not solve the error with the ID
错误:回溯(最后一次调用):文件“flame.py”,第24行,cur.execute(“插入到flame(ID,flame,)值(%s,%s)”,[ID,flame])NameError:name'ID'未定义编辑字面上表示stacktrace-1中错误的代码格式无法读取。