Arduino +RS485温湿度传感器

传感器参数如下

在这里插入图片描述
RS485传感器的通讯协议是modbus协议
比如读取温度,发送:01 03 00 00 00 01 84 0A
返回:01 03 04 01 13 00 01 CB CA
即 256 * 1 + 16 * 1 + 3 = 275 (对应温度:27.5℃)

设备

电源头、RS485温湿度传感器、Arduino UNO R3、RS485转TTL模块

连线

arduino 7号(TX)连接 TTL板 TX
arduino 8号(RX)连接TTL板RX

代码

#include <SoftwareSerial.h>
unsigned char item[8] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B}; //16进制测温命令
String data = “”; // 接收到的16进制字符串
SoftwareSerial tempSerial(8, 7); // RX, TX

float getTemp(String temperature); // 函数声明

void setup()
{
tempSerial.begin(9600);
Serial.begin(9600);
}

void loop()
{
delay(500); // 放慢输出频率
for (int i = 0 ; i < 8; i++) { // 发送测温命令
tempSerial.write(item[i]); // write输出
}
delay(100); // 等待测温数据返回
data = “”;
while (tempSerial.available()) {//从串口中读取数据
unsigned char in = (unsigned char)tempSerial.read(); // read读取
// Serial.print(in, HEX);
// Serial.print(‘,’);
data += in;
data += ‘,’;
}

while (Serial.available()) {//从串口中读取数据
unsigned char in = (unsigned char)Serial.read(); // read读取

data += in;
data += ',';

}

if (data.length() > 0) { //先输出一下接收到的数据

Serial.println(“Temp=”);
Serial.print(getTemp(data));
Serial.println(" Humi=");
Serial.print(getHumi(data));

}
}

float getHumi(String temp) {
int commaPosition = -1;
String info[9]; // 用字符串数组存储
for (int i = 0; i < 9; i++) {
commaPosition = temp.indexOf(‘,’);
if (commaPosition != -1)
{
info[i] = temp.substring(0, commaPosition);
temp = temp.substring(commaPosition + 1, temp.length());
}
else {
if (temp.length() > 0) { // 最后一个会执行这个
info[i] = temp.substring(0, commaPosition);
}
}
}
return (info[3].toInt() * 256 + info[4].toInt()) / 10.0;
}

float getTemp(String temp) {
int commaPosition = -1;
String info[9]; // 用字符串数组存储
for (int i = 0; i < 9; i++) {
commaPosition = temp.indexOf(‘,’);
if (commaPosition != -1)
{
info[i] = temp.substring(0, commaPosition);
temp = temp.substring(commaPosition + 1, temp.length());
}
else {
if (temp.length() > 0) { // 最后一个会执行这个
info[i] = temp.substring(0, commaPosition);
}
}
}
return (info[5].toInt() * 256 + info[6].toInt()) / 10.0;
}

  • 4
    点赞
  • 69
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

生活热爱就好

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值