arduino模拟modbus从站
个人笔记,请勿言论
模拟温湿度模块,随机温湿度
代码:
#include <Arduino.h>
#include <ModbusMaster.h>
const int bufferLength = 10; // 定义缓存大小为10个字节
char serialBuffer[bufferLength]; // 建立字符数组用于缓存
/*将多个char十六进制字符拼接成一个char字符(如0和a拼接成0x0a)*/
unsigned char catChar2Hex(unsigned char hByte, unsigned char lByte)
{
unsigned char ucTmp = 0x00;
unsigned char hight;
unsigned char low;
if ((hByte >= 'A') && (hByte <= 'F'))
{
hight = hByte - 'A' + 10;
}
else if (hByte >= 'a' && hByte <= 'f')
{
hight = hByte - 'a' + 10;
}
else if (hByte >= '0' && hByte <= '9')
{
hight = hByte - '0';
}
else
{
ucTmp = 0xff;
}
if ((lByte >= 'A') && (lByte <= 'F'))
{
low = lByte - 'A' + 10;
}
else if (lByte >= 'a' && lByte <= 'f')
{
low = lByte - 'a' + 10;
}
else if (lByte >= '0' && lByte <= '9')
{
low = lByte - '0';
}
else
{
ucTmp = 0xff;
}
ucTmp = (hight << 4) | (low << 0); //高位左移4位,低位不移动,组成一个8位十六进制字符
return ucTmp;
}
void red_adder_sum(char redBuffer[])
{
int redbufferLength = 0;
uint16_t u16CRC = 0xFFFF;
if (redBuffer[5] == 1)
{
redbufferLength = 7;
}
else if (redBuffer[5] == 2)
{
redbufferLength = 9;
}
char sendBuffer[redbufferLength]; // 建立字节数组用于缓存
sendBuffer[0] = redBuffer[0]; //地址
sendBuffer[1] = redBuffer[1]; //功能码
char temperature[4] = {0}; //存放温湿度值的十六进制
char humidity[4] = {0};
sprintf(temperature, "%X", random(3000, 65535));
sprintf(humidity, "%X", random(8000, 10000));
switch (redBuffer[5])
{
case 1:
sendBuffer[2] = 2; //数据长度
sendBuffer[3] = catChar2Hex(temperature[0], temperature[1]);
sendBuffer[4] = catChar2Hex(temperature[2], temperature[3]);
break;
case 2:
sendBuffer[2] = 4; //功能码
sendBuffer[3] = catChar2Hex(temperature[0], temperature[1]);
sendBuffer[4] = catChar2Hex(temperature[2], temperature[3]);
sendBuffer[5] = catChar2Hex(humidity[0], humidity[1]);
sendBuffer[6] = catChar2Hex(humidity[2], humidity[3]);
break;
default:
break;
}
for (int s = 0; s < redbufferLength - 2; s++)
{
u16CRC = crc16_update(u16CRC, sendBuffer[s]);
}
sendBuffer[redbufferLength - 2] = lowByte(u16CRC);
sendBuffer[redbufferLength - 1] = highByte(u16CRC);
delay(100);
for (int i = 0; i < redbufferLength; i++)
{ // 然后通过串口监视器输出readBytes
Serial.print(sendBuffer[i]); // 函数所读取的信息
}
}
void setup()
{
// 启动串口通讯
Serial.begin(9600);
Serial.println();
}
void loop()
{
if (Serial.available())
{ // 当串口接收到信息后
Serial.readBytes(serialBuffer, bufferLength); // 将接收到的信息使用readBytes读取
red_adder_sum(serialBuffer);
delay(100);
}
}