波特率都是4800 设备地址 默认01 广播FF
#define mySerial Serial2 byte Msg_getdata[8]={0x01,0x03,0x00,0x00,0x00,0x02,0xC4,0x0B}; char RecData[9]={0}; //==============校验============== uint16_t modbus_crc16( char *data, uint8_t length) { uint16_t crc = 0xFFFF; for (uint8_t i = 0; i < length; i++) { crc ^= data[i]; for (uint8_t j = 8; j > 0; j--) { if (crc & 0x0001) { crc = (crc >> 1) ^ 0xA001; } else { crc >>= 1; } } } return crc; } // CRC16 校验 // char senddata[6] = {0x30,0x31,0x00,0x00,0x00,0x02}; // 数据 数据长度(不包含校验码本身) // uint16_t crc = modbus_crc16(senddata, sizeof(senddata)); // // //CRC16: 0xB, 0xC4 // uint16_t crc_H= (crc & 0xFF00) >> 8; // uint16_t crc_L= (crc & 0x00FF); // // Serial.print("CRC16: 0x"); // Serial.print(crc_H, HEX); // Serial.print(", 0x"); // Serial.println(crc_L, HEX); /* 0~9 48~57 30~39H A~Z 65~90 41~5AH a~z 97~122 61~7AH 空格 32 20H */ void setup() { Serial.begin(4800); mySerial.begin(4800); } void loop() { delay(3000); mySerial.write(Msg_getdata,sizeof(Msg_getdata)) ; while(1){ if(mySerial.available()>0)//判断串口是否有数据可读 { delay(50); for(int i=0;i<9;i++) { RecData[i]=mySerial.read(); //Serial.print(i); Serial.print(" - ");Serial.println(RecData[i]); } // 地址 功能码 数据长度 风速寄存器0高 风速寄存器0低 风级寄存器1高 风级寄存器1低 CRC16低校验码 CRC16高校验码 // 01 03 00 00 24 00 03 FA 39 uint16_t crc = modbus_crc16(RecData, sizeof(RecData)-2);// 最后两位是校验码 //CRC16: 0xB, 0xC4 uint16_t crc_H= (crc & 0xFF00) >> 8; uint16_t crc_L= (crc & 0x00FF); uint16_t crc_L_rec=RecData[7]; uint16_t crc_H_rec=RecData[8]; if(crc_L_rec=crc_L && crc_H_rec==crc_H) { float fengsu=(RecData[4])/10.0; int dnegji =(RecData[6]); String showms=" 风速: " + String(fengsu)+"m/s 等级:"+String(dnegji); Serial.println(showms); break; } else{ Serial.println("校验失败......"); Serial.print("接收的CRC16: 0x"); Serial.print(crc_L, HEX); Serial.print(", 0x"); Serial.print(crc_H, HEX); Serial.print(" 计算的CRC16: "); Serial.print(crc_L_rec, HEX); Serial.print(", 0x"); Serial.println(crc_H_rec, HEX); break; } } delay(20); } }
标签:crc,HEX,stm32,ardunio,uint16,风速,print,rec,Serial From: https://www.cnblogs.com/gooutlook/p/17777957.html