libmodbus - Linux, Mac OS, FreeBSD, Windows 용 Modbus 라이브러리

freeFree Technical Resource

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

libmodbus - Linux, Mac OS, FreeBSD, Windows 용 Modbus 라이브러리

개 요

lib mod bus 는 전통적인 RS - 23 2, RS - 42 2, RS - 48 5 및 이 더 넷 장치를 지원 하는 빠르고 이 식 가능한 Mod bus 라이 브 러 리 입니다 .

설치

Linux、MacOS、FreeBSD、WIN32等可直接経由包管理器インストール

lib mod bus 공식 웹 사이트 다운로드 : www . example . com https://libmodbus.org/releases/libmodbus-3.1.7.tar.gz

/ / 압 축 해 제 디 렉 토 리로 이동 합니다 .
cd lib mod bus - 3. 1. 7
/ / 구성 컴 파 일 옵션 (예 : AR M , -- build 은 시스템 아 키 텍 처 , -- host 는 컴 파 일 시스템 도구 체 인 , -- pre fix 는 출 력 디 렉 토 리 , 옵션 은 모두 선택 적)
./ configure --build=i686 --host=arm-linux --enable-static --prefix=
/ / 컴 파 일 설치
make make 설치 하기&&

예 제

R TU 마스터

# include st dio . h<>
#include >
#include >
# include " mod bus . h "

int main (vo id)
{ 
    int i = 0 ;
    int reg s = 0 ;
    mod bus _ t * c t x = N ULL ;
    uint16_t tab_reg

    / / Open port : 포 트 , 보 트 속도 , 체크 비트 , 데이터 비트 , 중지 비트
    c t x = mod bus _ new _ r tu ("/ dev / tt y US B 0 ", 96 00, ' N ', 8, 1);
    / / 슬 레이 브 주소 설정
    mod bus _ set _ slave (ct x , 1);
    / / 직 렬 포 트 모 드 설정 (선 택 사항)
    mod bus _ r tu _ set _ serial _ mode (ct x , MO DB US _ R TU _ RS 48 5) ;
    / / R TS 설정 (선 택 사항)
    mod bus _ r tu _ set _ r ts (ct x , MO DB US _ R TU _ R TS _ UP);
    / / 연결 만들기
    if (mod bus _ connect (ct x) == - 1) {
        f print f (st der r , " 연 결 실패 : % s \ n ", mod bus _ str er ror (err no));
        mod bus _ free (ct x)
        return - 1;
    }
    / / 응답 지 연 설정 (선 택 사항)
    mod bus _ set _ response _ time out (ct x , 0, 100 0000);

    while (1)
    {
        mem set (tab _ reg , 0, size of (tab _ reg));
        읽기 레 지 스터 설정 : 레 지 스터 주소 , 수 량 , 데이터 버 퍼
        reg s = mod bus _ read _ register s (ct x , 0, 20, tab _ reg);
        if (r c == - 1) {
           f print f (st der r , " % s \ n ", mod bus _ str er ror (err no));
           계속 ;
        }
        printf("
        for (i = 0; i 
        {
            printf("
        }
        print f ( " \ n ");
        잠 들 다 (1)
    }
}
  • R TU - Master 프로세 스 요 약 :
  1. mod bus 포인 터 초기 화
  2. 슬 레이 브 스테 이션 ID 설정
  3. 연결 설정
  4. 읽기 유지 레 지 스터 / 입력 레 지 스터 / 이 산 입력 / 코 일 입력
  5. 단일 레 지 스터 / 다 중 레 지 스터 / 다 중 비트 데이터 쓰 기
  6. 연결 닫 기

R TU 슬 레이 브

# include st dio . h<>
#include >
#include >
#include >
#include >
# include " mod bus . h "

int main (vo id)
{ 
    int i = 0 ;
    int r c = 0 ;
    mod bus _ t * c t x = N ULL ;
    mod bus _ mapp ing _ t * mb _ mapp ing = N ull ;
    uint8_t query

    / / Open port : 포 트 , 보 트 속도 , 체크 비트 , 데이터 비트 , 중지 비트
    c t x = mod bus _ new _ r tu ("/ dev / tt y US B 0 ", 96 00, ' N ', 8, 1);
    / / 슬 레이 브 주소 설정
    mod bus _ set _ slave (ct x , 1);
    S erial Mode 설정
    mod bus _ r tu _ set _ serial _ mode (ct x , MO DB US _ R TU _ RS 48 5)
    R TS 설정
    / / mod bus _ r tu _ set _ r ts (ct x , MO DB US _ R TU _ R TS _ UP);
    / / 연결 만들기
    if (mod bus _ connect (ct x) == - 1) {
        f print f (st der r , " 연 결 실패 : % s \ n ", mod bus _ str er ror(errno));
        modbus_free(ctx);
        return -1;
    }
    mb_mapping = modbus_mapping_new(MODBUS_MAX_READ_BITS, 0,
                                    MODBUS_MAX_READ_REGISTERS, 0);
    if (mb_mapping == NULL) {
        fprintf(stderr, "Failed to allocate the mapping: %s\n",
                modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }

   //初期化几1つのレジスタ
   mb_mapping->tab_registers[0] = 1;
   mb_mapping->tab_registers[1] = 2;
   mb_mapping->tab_registers[2] = 3;
   mb_mapping->tab_registers[3] = 4;
   mb_mapping->tab_registers[4] = 5;
   mb_mapping->tab_registers[5] = 6;

    while (1)
    {
        memset(query, 0, sizeof(query));
        rc = modbus_receive(ctx, query);
        if (rc > 0) {
            modbus_reply(ctx, query, rc, mb_mapping);
        } else if (rc  == -1) {
            //Connection closed by the client or error
            break;
        }
    }

    printf("Quit the loop: %s\n", modbus_strerror(errno));

    modbus_mapping_free(mb_mapping);
    if (s != -1) {
        close(s);
    }
    modbus_close(ctx);
    modbus_free(ctx);
}

RTU-Slave流程总结:

  1. 初期化 modbus 指针;
  2. 設定スレーブID;
  3. modbus_mapping_new初期化レジスタ,戻る一个modbus_mapping_t 指针;
  4. 建立连接;
  5. 调用 modbus_receive 函数判断シリアルポート的受信データ,负责受信処理及回复。

TCP master

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <error.h>
#include <memory.h>
#include <sys/socket.h>
#include "modbus.h"

void main(void)
{
    int i;
    int regs = 0;
    int num = 0;
    modbus_t *ctx = NULL;
    uint16_t tab_reg[64] = {0};
   
    ctx = modbus_new_tcp("127.0.0.1",8000);
    modbus_set_slave(ctx, 1);
    modbus_connect(ctx);
    modbus_set_response_timeout(ctx, 0, 1000000);
   
    while (1)
    {
        memset(tab_reg, 0, sizeof(tab_reg));
        regs = modbus_read_registers(ctx, 0, 20, tab_reg);
        printf("[%4d][read num = %d]", num++, regs);
        for (i = 0; i < 20; i++)
        {
            printf("<%#x>", tab_reg[i]);
        }
        printf("\n");
        sleep(1);
    }

    modbus_close(ctx);
    modbus_free(ctx);
}

TCP slave

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <error.h>
#include <memory.h>
#include <sys/socket.h>
#include "modbus.h"

int main(void)
{ 
    int i = 0;
    int rc = 0;
    modbus_t *ctx = NULL;
    modbus_mapping_t *mb_mapping = NULL;
    uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];

    //打开ポート: ip, port
    ctx = modbus_new_tcp("127.0.0.1", 8000);
    //設定スレーブアドレス
    modbus_set_slave(ctx, 1);
    //建立连接
    if (modbus_connect(ctx) == -1) {
        fprintf(stderr, "Connexion failed: %s\n", modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }
    mb_mapping = modbus_mapping_new(MODBUS_MAX_READ_BITS, 0,
                                    MODBUS_MAX_READ_REGISTERS, 0);
    if (mb_mapping == NULL) {
        fprintf(stderr, "Failed to allocate the mapping: %s\n",
                modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }

   //初期化几1つのレジスタ
   mb_mapping->tab_registers[0] = 1;
   mb_mapping->tab_registers[1] = 2;
   mb_mapping->tab_registers[2] = 3;
   mb_mapping->tab_registers[3] = 4;
   mb_mapping-
   mb_mapping-

    while (1)
    {
        mem set (qu ery , 0, size of (qu ery))
        r c = mod bus _ receive (ct x , quer y)
        if (rc 
            mod bus _ reply (ct x , quer y , r c , mb _ mapp ing)
        } else if (r c == - 1) {
            클 라이언 트에 의해 연결 이 닫 혔 거나 오류 가 발생 했습니다 .
            break ; break ;
        }
    }

    print f (" Qu it the loop : % s \ n ", mod bus _ str er ror (err no));

    mod bus _ mapp ing _ free (mb _ mapp ing);
    if (s ! =) - 1) {
        닫 기 (s);
    }
    mod bus _ close (ct x);
    mod bus _ free (ct x)
}

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

《 “libmodbus - Linux, Mac OS, FreeBSD, Windows 용 Modbus 라이브러리” 》 有 6 条コメント

Leave a Reply

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