I have created a temperature sensor (using DS18B20 temperature sensor) and wrote the python program to read and display the temperature every 10 seconds. It worked fine. Later, I modified the code to save the recordings of each 10 sec to a MySQL database. Now, the problem is that it records AND uploads the data to the databse for the first time it reads. Then, I get an error message. So basically, the program reads and uploads to the database for once and then quits after the error. Please tell me how to fix this! Thanks a lot!
Here is the code:
import os
import time
import MySQLdb
import datetime
i = datetime.datetime.now()
db = MySQLdb.connect(host = "localhost", user = "root", passwd = "bb9125ap", db = "PY1")
cur = db.cursor()
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
temp_sensor = '/sys/bus/w1/devices/28-00042d6745ff/w1_slave'
def temp_raw():
f = open(temp_sensor,'r')
lines = f.readlines()
f.close
return lines
def read_temp():
lines = temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = temp_raw()
temp_output = lines[1].find('t=')
if temp_output != -1:
temp_string = lines[1].strip()[temp_output+2:]
temp_c = float(temp_string) / 1000.0
return temp_c
while True:
print "recording data into database(period = 5s.)....press ctrl+Z to stop!"
valT = str(read_temp())
year = str(i.year)
month = str(i.month)
day = str(i.day)
date = day + "-" + month + "-" + year
hour = str(i.hour)
minute = str(i.minute)
second = str(i.second)
time = hour + ":" + minute + ":" + second
try:
cur.execute("""INSERT INTO PY1.DUMP1(temp_c,rec_time,rec_date) VALUES(%s,%s,%s)""",(valT,time,date))
db.commit()
except:
db.rollback()
time.sleep(10)
cur.close()
db.close()
Program name is temp1.py and line 54 according to my editor is db.rollback() Here is the error message I get
Traceback (most recent call last): File "temp1.py" , line 54 , in time.sleep(10) Attribute:'str' object has no attribute 'sleep'
您正在用本地变量时间覆盖导入的时间,并将其转换为字符串。
time = hour + ":" + minute + ":" + second
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.