Beispiel #1
0
 public static UInt16 Modbus_Read03Command(Byte devAddr, UInt16 regAddr, UInt16 regLen)
 {
     Byte[] tmpbuf = new Byte[16];
     tmpbuf[0] = devAddr;                      // 设备地址
     tmpbuf[1] = 0x03;                         // 0x03
                                               // 寄存器起始地址 0000-FFFF
     tmpbuf[2] = (byte)(regAddr >> 8);         // 高地址
     tmpbuf[3] = (byte)(regAddr & 0xFF);       // 低地址
                                               // 读取N(1-125)个寄存器
     tmpbuf[4] = (byte)(regLen >> 8);          // 长度高
     tmpbuf[5] = (byte)(regLen & 0xFF);        // 长度低
     if (regLen > 125)
     {
         return(0);
     }
     Modbus.ModbusSend_WriteCommand(6, tmpbuf);
     return(1);
     // 应答:      01(1字节地址) 03(1字节功能), 02(1字节数据长度字节), 00 00(2字节数据)
     // 错误应答:  01(1字节地址) 83(1字节功能), 01(01/02/03/04 1个字节,错误类型)
     // 必须记录发送命令的地址,否则没有办法区分
 }
Beispiel #2
0
        public static UInt16 Modbus_Write10Command(Byte devAddr, UInt16 regAddr, UInt16 regLen, UInt16[] dat)
        {
            Byte[] tmpbuf = new Byte[255];
            UInt16 tmpdat;

            tmpbuf[0] = devAddr;                       // 设备地址 地址码, 1字节
            tmpbuf[1] = 0x10;                          // 功能0x10, 1字节
                                                       // 寄存器地址, 2字节
            tmpbuf[2] = (byte)(regAddr >> 8);          // 高地址
            tmpbuf[3] = (byte)(regAddr & 0xFF);        // 低地址

            UInt16 writelen = regLen;                  // 写入N个(数值1-123)寄存器,2字节

            tmpbuf[4] = (byte)(writelen >> 8);         // 长度高
            tmpbuf[5] = (byte)(writelen & 0xFF);       // 长度低

            writelen  = (UInt16)(writelen * 2);        // 写入2*N(数值2-246)个字节, 1字节
            tmpbuf[6] = (byte)(writelen);              // 字节

            UInt16 ptr = 7;

            // 写一个数据到寄存器,2字节
            for (int i = 0; i < regLen; i++)
            {
                tmpdat      = dat[i];
                tmpbuf[ptr] = (byte)(tmpdat >> 8);              // 数据高
                ptr         = (UInt16)(ptr + 1);
                tmpbuf[ptr] = (byte)(tmpdat & 0xFF);            // 数据低
                ptr         = (UInt16)(ptr + 1);
            }

            Modbus.ModbusSend_WriteCommand(ptr, tmpbuf);
            return(1);
            // 应答:      01(1字节地址) 10(1字节功能), XXXX(2字节,寄存器始地址), 00 00(2字节,寄存器长度)
            // 错误应答:  01(1字节地址) 90(1字节功能), 01(01/02/03/04 1个字节,错误类型)
            // 必须记录发送命令的地址,否则没有办法区分
        }