为什么我的代码不能在python上运行这些代码?

9rbhqvlz  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(351)

我正在用最新的raspbian软件在我的raspberrypi3上运行python3(idle)代码。通过这段代码,我试图通过ds18b20传感器获取温度数据,并将相同的数据发送到我创建的mysql数据库。
非常感谢您的帮助!
从这段代码中执行出来的是:

Connected to MySQL database... MySQL Server version on  5.5.5-10.1.37-MariaDB-0+deb9u1
Your connected to -  ('temp_pi',)

也就是说mysql数据库之间已经建立了连接。但这段代码的目标是通过ds18b20传感器获取温度数据,并将相同的数据发送到tab\ U表格中。

import os
import glob
import time
import MySQLdb
import datetime
import mysql.connector
from mysql.connector import Error

i = datetime.datetime.now()

# Establish the connection to the mysql database.

try:
    connection = mysql.connector.connect(host='127.0.0.1',
                             database='temp_pi',
                             user='root',
                             password='test')

    if connection.is_connected():
       db_Info = connection.get_server_info()
       print("Connected to MySQL database... MySQL Server version on ",db_Info)
       cursor = connection.cursor()
       cursor.execute("select database();")
       record = cursor.fetchone()
       print ("Your connected to - ", record)

except Error as e :
    print ("Error while connecting to MySQL", e)

# Obtain the temperature data through the ds18b20 sensor.

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c  

    # Send the temperature data into a specific table entitled TAB_CLASSROOM.   
    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)
            timestr = hour + ":" + minute + ":" + second

            try:
                cur.execute("""INSERT INTO TAB_CLASSROOM(temp_c,T_Date,T_Time) VALUES(%s,%s,%s)""",(valT,date,timestr))
                db.commit()
            except:
                db.rollback()

            time.sleep(10)

    cur.close()  
    db.close()
y1aodyip

y1aodyip1#

你还没打电话 read_temp 函数,代码只定义它。
这个 while True 是凹入的,这意味着它是 read_temp 功能。也许你想把凹痕从那里一直去掉。
那样的话 while True: 已执行。

相关问题