日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Modbus通信及數據存儲讀取

作者:lzfshub 更新時間: 2024-03-06 編程語言

1. 存儲區代號

代碼號 功能
1區 輸入線圈
0區 輸出線圈
3區 輸入寄存器
4區 輸出寄存器

2. 功能碼

代碼 功能
0x01 讀取輸出線圈
0x02 讀取輸入線圈
0x03 讀取輸出寄存器
0x04 讀取輸入寄存器
0x05 寫入單個線圈
0x06 寫入單個寄存器
0x0F 寫入多個線圈
0x10 寫入多個寄存器

3. pymodbus服務器

from pymodbus.server.async_io import StartTcpServer
from pymodbus.datastore import (
    ModbusSequentialDataBlock,
    ModbusServerContext,
    ModbusSlaveContext,
)

datablock = ModbusSequentialDataBlock.create()
context = ModbusSlaveContext(
    di=datablock,
    co=datablock,
    hr=datablock,
    ir=datablock,
    )
single = True

# Build data storage
store = ModbusServerContext(slaves=context, single=single)


if __name__ == '__main__':

	address = ("127.0.0.1", 1502)
	StartTcpServer(
	    context=store,  # Data storage
	    address=address,  # listen address
	  	allow_reuse_address=True,  # allow the reuse of an address
	)

4. libmodbus客戶端

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <modbus/modbus.h>
#include <time.h>


// const uint16_t UT_INPUT_REGISTERS_ADDRESS = 0x1;
const uint16_t UT_BITS_ADDRESS = 0x04;
// const uint16_t UT_INPUT_REGISTERS_NB = 0xA;
// const uint16_t UT_INPUT_REGISTERS_TAB[] = { 0x000A };

int main(int argc, char const *argv[])
{
    int nb = 0x08;
    int rc = 0;
    modbus_t *ctx;
    uint8_t *tab_rp_bits;
    tab_rp_bits = (uint8_t *) malloc(nb * sizeof(uint8_t));
    memset(tab_rp_bits, 0, nb * sizeof(uint8_t));
    ctx = modbus_new_tcp("127.0.0.1", 1502);
    if(ctx == NULL)
    {
        fprintf(stderr, "Unable to allocate libmodbus context\n");
        return -1;
    }

    if(modbus_connect(ctx) == -1)
    {
        fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }
    uint8_t data[8] = {1, 0, 1, 0, 1, 1, 0, 1};
    while(1)
    {
        // rc = modbus_write_bit(ctx, UT_BITS_ADDRESS, 1);
        rc = modbus_write_bits(ctx, UT_BITS_ADDRESS, nb, data);
        printf("nb points %d : ", rc);

        rc = modbus_read_bits(ctx, UT_BITS_ADDRESS, 8, tab_rp_bits);
        if (rc != 1) 
        {
            for (size_t i{0}; i < 8; i++)
                // printf("FAILED (nb points %d)\n", rc);
                printf("%d  ", tab_rp_bits[i]);
        }
        printf("\n");
        memset(tab_rp_bits, 0, nb * sizeof(uint8_t));
        sleep(1);
    }
    modbus_close(ctx);
    modbus_free(ctx);
    return 0;
}

原文鏈接:https://blog.csdn.net/weixin_40511249/article/details/128190018

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新