【发布时间】:2020-03-11 21:45:43
【问题描述】:
希望你们一切都好。
我有一个问题,我已经尝试解决了很长时间,但没有成功。
我编写了这个 Arduino 脚本,它读取 DHT11 传感器注册的值并将它们打印到串行。代码如下:
#include <dht11.h>
#define DHT11PIN 2
dht11 DHT11;
void setup()
{
Serial.begin(115200);
}
void loop()
{
Serial.println();
int chk = DHT11.read(DHT11PIN);
float h = DHT11.humidity; //read humidity
float t = DHT11.temperature; //read temperature (C)
Serial.print(h);
Serial.print("%");
Serial.print(t);
delay(2000);
}
我的目的是将上述数据打印在串行上,并将其发送到 python 代码,然后将接收到的数据插入到我创建的 MySQL 数据库中。在接收部分之前一切似乎都运行良好,但是当我尝试将接收到的数据插入我的数据库时,无论我如何处理数据,我都会遇到各种不同的错误。
首先,当我尝试使用下面的代码时:
#!/usr/bin/env python3
import serial
import mysql.connector as connector
import re
#the following have been changed so that I don't expose the real details
__dsn = {
"host": "localhost",
"user": "user",
"passwd": "passwd",
"db": "sensor"
}
dbConn = connector.connect(**__dsn)
#open a cursor to the database
cursor = dbConn.cursor()
ser = serial.Serial('/dev/ttyACM0', 115200)
humidity = 0
temperature = 0
while 1:
#data = ser.read()
data = ser.read(1)
n = ser.inWaiting()
if n:
data = data + ser.read(n)
data = data.decode("UTF-8")
try:
pieces = data.split('%') #split the data by the tab
humidity = pieces[0]
temperature = pieces[1]
except IndexError:
pass
a = humidity
b = temperature
cursor.execute("INSERT INTO environment(humidity,temperature) VALUES (%s,%s)", (a,b))
dbConn.commit()
cursor.close()
我收到此错误:
我也尝试将湿度和温度值都更改为浮点类型,但如果这样做,我会收到以下错误:
我不确定这里发生了什么。我尝试以多种方式处理数据。以下是我迄今为止尝试使用的数据处理方法的示例:
humidity.replace(" ", "")
temperature.replace(" ", "")
a = float(humidity).notnull()
b = float(temperature).notnull()
float(re.sub(r'[^0-9\.]', '', a))
float(re.sub(r'[^0-9\.]', '', b))
再一次,没有成功...
如果有人能指出我正确的方向,我将不胜感激。
谢谢
罗伯
【问题讨论】:
-
您似乎在发送数字数据,但随后您尝试在 python (
data.decode("UTF-8")) 中将其视为字符串。这对我来说听起来不对! -
您是否还可以添加您尝试插入数据库的值以及环境的创建表
-
如果您将
print(data)放在data = data.decode("UTF-8")的正下方,我想您会立即看到问题所在... -
嗨。感谢您的所有回答。我一直在尝试根据您的建议修复我的代码。当我从代码中删除 data.decode("UTF-8) 行时,我收到以下错误:“不需要'str'”。Arduino 发送一个“%”符号以及值被视为可能是问题所在的字符串。我将不胜感激任何进一步的建议。非常感谢你们。
标签: python mysql arduino raspberry-pi