uplifting_mind
Newbie level 6
Hello,
I trying to make program for building and sending Modbus RTU packet. Program contain a function for CRC. Results of CRC must be two bytes placed in the end of packet. This is what I have yet, there is function for CRC and function send_packet(), which I call from main. But there is some error during compilation. I don´t know how to forward my packet[] array to CRC function. I don´t understand pointers very well.
Please help.
I trying to make program for building and sending Modbus RTU packet. Program contain a function for CRC. Results of CRC must be two bytes placed in the end of packet. This is what I have yet, there is function for CRC and function send_packet(), which I call from main. But there is some error during compilation. I don´t know how to forward my packet[] array to CRC function. I don´t understand pointers very well.
Please help.
Code:
uint8_t packet[5];
int i;
int len;
uint16_t crc;
uint8_t crc_LByte;
uint8_t crc_HByte;
uint8_t *buf;
uint8_t pos;
// Compute the MODBUS RTU CRC
uint16_t ModRTU_CRC(uint8_t *buf, int len)
{
uint16_t crc = 0xFFFF;
for (int pos = 0; pos < len; pos++) {
crc ^= (uint16_t)*buf[pos]; // XOR byte into least sig. byte of crc
for (int i = 8; i != 0; i--) { // Loop over each bit
if ((crc & 0x0001) != 0) { // If the LSB is set
crc >>= 1; // Shift right and XOR 0xA001
crc ^= 0xA001;
}
else // Else LSB is not set
crc >>= 1; // Just shift right
}
}
// Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes)
return crc;
}
void send_packet(uint8_t address, uint8_t function, uint8_t lo_data, uint8_t hi_data) {
packet[0] = address; // build packet
packet[1] = function;
packet[2] = lo_data;
packet[3] = hi_data;
crc = ModRTU_CRC(packet, 4);
crc_LByte = (crc & 0x00FF); // Low byte calculation
crc_HByte = (crc & 0xFF00) / 256; // High byte calculation
packet[4] = crc_LByte;
packet[5] = crc_HByte;
for (i = 0; i < 6; i++) {
printf("%d %02x\n", i, (int) packet[i]); // send packet
}
}