Commit ddfbae87 authored by 学习的菜鸟's avatar 学习的菜鸟

删除了

parent 42ea7193
#include <Arduino.h>
HardwareSerial mySerial(2); // UART2
#define TXD2 17
#define RXD2 16
#define RX_MAX 128
uint8_t variable[RX_MAX];
int index = 0;
typedef struct {
int16_t x;
int16_t y;
int16_t angle;
int16_t c;
int16_t line;
} PGV_H;
PGV_H Last_cal_data_hds;
// CRC16-Modbus 校验函数
uint16_t Modbus_CRC16(const uint8_t *buf, uint8_t len) {
uint16_t crc = 0xFFFF;
for (uint8_t pos = 0; pos < len; pos++) {
crc ^= (uint16_t)buf[pos];
for (uint8_t i = 0; i < 8; i++) {
if ((crc & 0x0001) != 0) {
crc >>= 1;
crc ^= 0xA001;
} else {
crc >>= 1;
}
}
}
return crc;
}
void update_data() {
if ((variable[0] == 0x01) && (variable[1] == 0x03) && (variable[2] == 0x0A)) {
uint16_t received_crc = variable[13] | (variable[14] << 8);
uint16_t calc_crc = Modbus_CRC16(variable, 13);
if (received_crc != calc_crc) {
Serial.println("CRC 校验失败!");
return;
}
Last_cal_data_hds.x = ((uint16_t)variable[3] << 8) + variable[4];
Last_cal_data_hds.y = ((uint16_t)variable[5] << 8) + variable[6];
Last_cal_data_hds.angle = ((uint16_t)variable[7] << 8) + variable[8];
Last_cal_data_hds.c = ((uint16_t)variable[9] << 8) + variable[10];
Last_cal_data_hds.line = ((uint16_t)variable[11] << 8) + variable[12];
Serial.printf("X: %d, Y: %d, Angle: %d, Color: %d, Line: %d\n",
Last_cal_data_hds.x,
Last_cal_data_hds.y,
Last_cal_data_hds.angle,
Last_cal_data_hds.c,
Last_cal_data_hds.line);
}
}
void setup() {
mySerial.begin(115200, SERIAL_8N1, RXD2, TXD2);
Serial.begin(115200);
Serial.println("PGV 系统初始化完成");
}
void loop() {
const uint8_t base_cmd[] = {0x01, 0x03, 0x00, 0x3B, 0x00, 0x06};
uint8_t full_cmd[8];
memcpy(full_cmd, base_cmd, 6);
uint16_t crc = Modbus_CRC16(full_cmd, 6);
full_cmd[6] = crc & 0xFF;
full_cmd[7] = (crc >> 8) & 0xFF;
mySerial.write(full_cmd, 8);
delay(100);
index = 0;
while (mySerial.available() && index < RX_MAX) {
variable[index++] = mySerial.read();
}
if (index >= 15) { // 13字节数据 + 2字节 CRC
update_data();
}
delay(500);
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment