aduino做主站通过modbus通讯读取温湿度
水平有限,仅供参考
带485口的温湿度模块
这里我用的是自定义的串口,最大波特率只有9600,串口1的波特率可以115200
实际操作还需要个TTL转485的模块,我这里用的是TTL转USB的模块,我想接线大家应该都懂就不做解释了。
看结果
我在模拟时需要在接收到信息的1s内点发送
代码如下:
需要先下载 ModbusMaster 库文件
#include <ModbusMaster.h>
#include <SoftwareSerial.h>
ModbusMaster node; // instantiate ModbusMaster object
SoftwareSerial BTserial(4, 5); // 建立SoftwareSerial对象,RX引脚4, TX引脚5
uint16_t temperature =0;
uint16_t humidity =0;
void setup()
{
Serial.begin(9600);
BTserial.begin(9600);
//in Modbus slave ID and serial
node.begin(10, BTserial);
// Callbacks allow us to configure the RS485 transceiver correctly
}
bool state = true;
void loop()
{
uint8_t result; //创建接收缓冲区
uint16_t sum_add = 1; //读取寄存器的起始地址
uint16_t sum_leng = 2;//读取寄存器的长度
result = node.readHoldingRegisters(sum_add, sum_leng);
//seng = 0A 03 00 01 00 02 94 B0
//red = 0A 03 04 30 39 26 94 84 31
if (result == node.ku8MBSuccess)
{
temperature = node.getResponseBuffer(0);
humidity = node.getResponseBuffer(1);
Serial.println(temperature);
Serial.println(humidity);
}
else
{
Serial.println("eroor");
}
delay(1000);
}