您好,欢迎访问代理记账网站
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

arduino模拟modbus从站

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);
  }
}


分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进