Example of Modbus Communication Code Based on 51 Single Chip Microcomputer

freeFree Technical Resource

This content is free to read, suitable for basic learning and search traffic.

Example of Modbus Communication Code Based on 51 Single Chip Microcomputer

The following is an example of Modbus communication code based on the 51 microcontroller, using Keil C compiler and STC89C52 microcontroller:

#include <reg52.h>

#define SlaveAddress 1      // 从机地址
#define FunctionCode 3      // 功能码
#define RegisterAddress 0   // 寄存器地址
#define RegisterLength 1    // 寄存器长度

sbit RS485_EN = P2^7;       // RS485芯片使能控制引脚

void delay(unsigned int i)  // 延时函数
{
    while(i--);
}

void UART_Init()            // 串口初始化函数
{
    SCON = 0x50;
    TMOD = 0x20;
    TH1 = 0xFD;
    TL1 = 0xFD;
    TR1 = 1;
}

void SendByte(unsigned char dat)  // 发送一个字节
{
    SBUF = dat;
    while(TI == 0);
    TI = 0;
}

void SendPacket(unsigned char address, unsigned char function, unsigned char* pData, unsigned char length) // 发送数据包
{
    unsigned char i, crcHi, crcLo;
    crcHi = 0xFF;
    crcLo = 0xFF;
    SendByte(0xFF);
    SendByte(0xFF);
    SendByte(address);
    SendByte(function);
    SendByte(RegisterAddress / 256);
    SendByte(RegisterAddress % 256);
    SendByte(RegisterLength / 256);
    SendByte(RegisterLength % 256);
    for(i = 0; i < length; i++)
    {
        SendByte(pData[i]);
        crcHi ^= pData[i];
        for(j = 0; j < 8; j++)
        {
            if(crcHi & 0x01)
            {
                crcHi >>= 1;
                crcHi ^= 0xA0;
            }
            else
            {
                crcHi >>= 1;
            }
        }
    }
    SendByte(crcHi);
    SendByte(crcLo);
}

void Modbus() // Modbus主函数
{
    unsigned char data[2] = {0, 0};
    SendPacket(SlaveAddress, FunctionCode, data, RegisterLength);
}

void main()
{
    UART_Init();
    while(1)
    {
        RS485_EN = 0;
        delay(1000);
        Modbus();
        delay(1000);
        RS485_EN = 1;
        delay(1000);
    }
}

Note: This code is only an example and for reference only. Specific implementation needs to be adjusted according to actual needs.

Put this resource to use in a real project?

Go to the Tool Center for message parsing, CRC verification and device debugging, or submit your requirements for selection and integration advice.

Engineer Membership

Turn this article into actionable debugging resources

After activation, you can use advanced message parsing, resource pack downloads, code examples, engineering cases and priority technical support, suitable for real project delivery.

Unlimited Advanced Tools
Resource & Code Packs
Complete Engineering Case Library
Priority Technical Support

Leave a Reply

Your email address will not be published. Required fields are marked *.