foreword
I recently took on a project that required the use of the Modbus protocol. Although I have heard of it before, I have never tried it in practice. But after practice, I found that it is actually very simple. I think it is essentially a "secondary encapsulation" of serial port transmission .
Suggested order of entry
- The Great God will take you to understand the Modbus communication protocol in seconds - understand the basic concepts
- STM32+RS485+Modbus-RTU (host mode + slave mode) - standard library / HAL library development - actual combat exercise
related software
In order to debug Modbus more conveniently, here are some recommended software:
- SSCOM : serial port debugging assistant, but has the function of automatically adding Modbus verification
- Modbus Poll : Simulate the Modbus host, the link is the official website download link, and the SN is
5A5742575C5D136F5843535610685C49434C1232131164706378
- Modbus Slave : Simulate Modbus slave, the link is the official website download link, SN is
54554154514756666A655A187D545E505C454F
Actual test: These two software seem to be unable to respond to the high baud rate of the hardware, so it is recommended not to set a high baud rate when communicating with the hardware, such as 115200.
CRC check code calculation function
This is the code implemented according to the procedure set by the protocol
void CRC16(unsigned char frame[], unsigned char length)
{
unsigned int crc16 = 0xffff;
unsigned char byteIndex, n;
for (byteIndex = 0; byteIndex < length - 2; byteIndex++)
{
crc16 ^= frame[byteIndex];
for (n = 0; n < 8; n++)
{
if (crc16 & 1)
{
crc16 >>= 1;
crc16 ^= 0xA001;
}
else
crc16 >>= 1;
}
}
frame[length - 2] = crc16; //记住,校验码低位在前,高位在后!
frame[length - 1] = crc16 >> 8;
}
There is also a list of all possible values on the Internet according to the law of XOR, and then directly index by subscript. It should actually run faster. If you are interested, you can find the relevant code, and I will not list it here.