目前只接收设备的数据区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();
}