这是我的第一个python脚本。我试图从Arduino上获取数据,在Raspberry Pi上读取数据并将其保存到数据库中。代码是分开工作的(我可以正确地分配变量并将数据发送到数据库,但似乎不能使它们都工作。我不确定我的逻辑是否有效(将变量设置为null,然后在它们都有值后保存)。谢谢你的意见
import re
import serial
import MySQLdb
import time
db =MySQLdb.connect(host = "localhost",user = "root",passwd = "example", db = "arduino")
ser =serial.Serial('/dev/ttyACM0',9600)
humidityPattern = "Humidity\:(\d\d\.\d\d)"
tempDhPattern = "TemperatureDH\:(\d\d\.\d\d)"
barometerPattern = "PressureBMP\:(\d\d\.\d\d)"
tempBmpPattern = "TemperatureBMP\:(\d\d\.\d\d)"
tempTmpPattern = "TemperatureTMP\:(\d\d\.\d\d)"
blLightPattern = "BLLight\:(\d+)"
brLightPattern = "BRLight\:(\d+)"
frLightPattern = "FRLight\:(\d+)"
flLightPattern = "FLLight\:(\d+)"
while 1:
line = ser.readline()
humidity = None
tempDh = None
pressure = None
tempBmp = None
tempTmp = None
blLight = None
brLight = None
frLight = None
flLight = None
#Humidity Sensor
m = re.match(humidityPattern, line)
if m is not None:
humidity = m.group(1)
print "Humidity is "+humidity
m = re.match(tempDhPattern, line)
if m is not None:
tempDh= m.group(1)
print "Humidity Temp is "+tempDh
#Pressure Sensor
m = re.match(barometerPattern, line)
if m is not None:
pressure = m.group(1)
print "Pressure is "+tempDh
m = re.match(tempBmpPattern, line)
if m is not None:
tempBmp= m.group(1)
print "Pressure Temp is "+tempBmp
#Temp Sensor
m = re.match(tempTmpPattern, line)
if m is not None:
tempTmp= m.group(1)
print "Temp is "+tempTmp
#Light Sensors
m = re.match(blLightPattern, line)
if m is not None:
blLight= m.group(1)
print "BL Light is "+ blLight
m = re.match(brLightPattern, line)
if m is not None:
brLight= m.group(1)
print "BR Light is "+ brLight
m = re.match(frLightPattern, line)
if m is not None:
frLight = m.group(1)
print "FR Light is "+ frLight
m = re.match(flLightPattern, line)
if m is not None:
flLight = m.group(1)
print "FL Light is "+ flLight
if humidity and tempDh and pressure and tempBmp and tempTmp and blLight and brLight and frLight and flLight is not None:
with db:
cur = db.cursor()
cur.execute('insert into weather(humidity, temp_dh, pressure,temp_bmp, temp_tmp, bl_light, br_light, fr_light, fl_light) values("%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s")'%(humidity, tempDh, pressure, tempBmp, tempTmp, blLight, brLight, frLight, flLight ))
time.sleep(5)
print 'upload'
测试中有一个问题:
它只测试
None
最后一个变量flLight
。但是,如果其他所有字符串都是None
或非空字符串,那么这个应该意外地起作用,因为None
是虚假的,每个非空字符串都是真实的所以一个更大的问题是,每次通过循环,你都会扔掉你以前读到的所有值,不管你是否保存了它们
要解决这个问题,请添加一个布尔标志
must_init
,并在循环的开始处将逻辑更改为:必须\u init=True 如果为真: line=ser.readline() 如果必须初始化: 湿度=无 tempDh=无 压力=无 tempBmp=无 MP=无 blLight=无 brLight=无 frLight=无 flLight=无 必须\u init=False
只在
with
语句的最后一个print 'upload'
之后的must_init = True
处再次设置must_init = True
这样,您将仅在(A)第一次或(B)将以前的值保存到DB之后立即清空所有变量,这似乎是更正确的逻辑
其他简化的改进是可能的(例如将变量作为dict中的项保留,这样就不必在
any
检查中枚举它们;在dict中使用与变量dict相同的名称键入重新表达式,以极大地压缩和简化您的代码),但关键点是,添加了must_init
布尔标志的代码,正如我之前所建议的,应该可以工作之后您可以改进它!-)相关问题 更多 >
编程相关推荐