ESP32+RS485监听设备(mosbus-RTU)

目前只接收设备的数据区0x04(电池电压)和0x06(电池电量)部分,需要接收不同部分可自行更改。本设备只用于监听,是一种slave,并非client模式。

#include <HardwareSerial.h>

HardwareSerial MySerial_esp32(1);

uint8_t needBytes[] = {0x01, 0x03, 0x02, 0xFF, 0xFF, 0xFF, 0xFF};
int needIndex = 0;

void read_usart(){

  if(MySerial_esp32.available() > 0){

    while(MySerial_esp32.available()) {
    
      uint8_t c = MySerial_esp32.read();
      
      if(needIndex < 3) {
        if(c != needBytes[needIndex]) {
          needIndex = 0;
          break; 
        }
      }
      
      if(needIndex >= 3 && needIndex < 7) {
        needBytes[needIndex] = c;
      }
      
      needIndex++;
      
      if(needIndex == 7) {
        if (needBytes[3] == 4 || needBytes[3] == 6)
        {
          // Serial.print("接收到的数据: ");
          // Serial.print(needBytes[3], HEX);   
          // Serial.print(" ");
          // Serial.println(needBytes[4], HEX);
          // int byteVlaue3 = needBytes[3];
          // int byteVlaue4 = needBytes[4];
          // Serial.print("转化成10进制的数据: ");
          // Serial.print(byteVlaue3);
          // Serial.print(" ");
          // Serial.println(byteVlaue4);
          if (needBytes[3] == 4 )
          {
            int Vlaue3 = ((needBytes[3] * 256) + needBytes[4])/100;
            Serial.print("电池电压:   ");
            Serial.println(String(Vlaue3)+"V");
          }
          if (needBytes[3] == 6 )
          {
            int Vlaue4 = ((needBytes[3] * 256) + needBytes[4])*100/3000;
            Serial.print("电池余量:   ");
            Serial.println(String(Vlaue4)+"%");
          }
          

          
        }
        
        //CRC-16/MODBUS	x16 + x15 + x2 + 1

        
        needIndex = 0;
        break;
      }
      
    }
    
  }
  
}

void setup() {

  Serial.begin(115200);

  MySerial_esp32.begin(9600, SERIAL_8N1, 16, 17);

}

void loop() {

  read_usart();
  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值