arduino传送字符串json到python解析为字典数据

您所在的位置:网站首页 python串口数据解析 arduino传送字符串json到python解析为字典数据

arduino传送字符串json到python解析为字典数据

#arduino传送字符串json到python解析为字典数据| 来源: 网络整理| 查看: 265

arduino

NO.1 前言

前几篇文章仅仅是将获取到的温湿度数据打印在串口,简单的字符串就可以,只需要查看,未实现存储.

为了方便的将arduino的数据使用python存到数据库中,使用json数据是一个不错的方式.

此处设计的为arduino传输的为字符串json,python将字符串转码为字典后然后进行数据处理.

NO.2 python字符转换

str转json

# 引入json模块 import json # 创建字符串json str = '{"temperature":27,"humidity":85}' # 解析为字典 j = json.loads(str) # 打印数据 print(j) # 打印数据类型 print(type(j))

获取到的结果为

{'temperature': 27, 'humidity': 85}

arduino

NO.3 arduino发送字符串

arduino如何拼接字符串

+运算符允许你把字符串和另一个字符串,常量字符数组,ASCII,变量,或者常量字符等组合起来。

// 字符串拼接数字 stringVal = stringOne + 123; ​ // 字符串拼接字符 stringVal = stringOne + "abc"; ​ // 两个字符串变量拼接 stringVal = stringOne + stringTwo;

arduino把温湿度拼接

参考代码注释

#include #define DHT11PIN 4 ​ dht11 DHT11; ​ void setup() { Serial.begin(9600); } ​ void loop() { Serial.println(); ​ // 初始化库 int chk = DHT11.read(DHT11PIN); ​ // 定义温度变量名 String temperature = "\"temperature\":"; // 获取温度 int temperatureNum=(float)DHT11.temperature;   // 定义湿度变量名 String humidity = "\"humidity\":"; // 获取湿度 int humidityNum=(float)DHT11.humidity;   // 拼接字符串json String dataRes="{"+temperature+temperatureNum+","+humidity+humidityNum+"}";   // 打印到串口 Serial.print(dataRes); ​ // 延时2s执行 delay(2000); ​ }

NO.4 python接收字符串

此处使用usb串口接收数据

注意,python接收到的为bytes字节符

b'{"temperature":28,"humidity":78}'

bytes转str方式

# 第一种 str(b'123', encoding='utf-8') # 第二种 bytes.decode(b'123')

python处理arduino传来的温湿度数据

参考代码注释

# 引入串口库(注意是serial,不是pyserial) import serial # 引入json库 import json ​ # 设置端口变量和值 serialPosrt = "COM3" # 设置波特率变量和值 baudRate = 9600 # 设置超时时间,单位为s timeout = 0.5 # 接受串口数据 ser = serial.Serial(serialPosrt, baudRate, timeout=timeout) ​ # 循环获取数据(条件始终为真) while 1:   # 读取接收到的数据的第一行   strData = ser.readline()   # 把拿到的数据转为字符串(串口接收到的数据为bytes字符串类型,需要转码字符串类型)   strJson = str(strData, encoding='utf-8')   # 如果有数据,则进行json转换   if strJson:       # 只有当检测到字符串中含有温湿度字符名时才进行json转码,其他的字符串内容不作操作       if "temperature" in strJson:           print("当前接受到的数据位->", strJson)           # 字符串转为json(每个字符串变量名必须为双引号包括,而不是单引号)           jsonData = json.loads(strJson)           print("转码成功,当前类型为->", type(jsonData))   else:       print("当前接收到的数据为空") ​

arduino

NO.5 总结

本文描述了数据通信的数据预处理和数据转码

python期望接收json数据,而不是无序的字符串流

将arduino的数据设置为字符串json格式(C/C++)

python将获取到的bytes字节符转为字符串(python)

python将字符串str转为json(字典)(python)

下期内容

使用sqlite等数据库存储arduino的传感器数据

END.



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3