51マイクロコントローラに基づくModbusCommunicationコード例

freeFree Technical Resource

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

51マイクロコントローラに基づくModbusCommunicationコード例

以下は、Keil CコンパイラとSTC89 C 52マイクロコントローラを使用した51マイクロコントローラベースのModbusCommunicationコードの例です。

#include <reg52.h>

#define SlaveAddress 1      // 从机地址
#define FunctionCode 3      // function code
#define RegisterAddress 0   // register address
#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);
    }
}

注:このコードは参考用の例であり、実装は実際のニーズに合わせて調整する必要があります。

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 *.