SOEM EtherCAT 示例:列出所有从站

以下 SOEM 示例列出所有从站。

它旨在与 SOEM (Simple Open EtherCAT Master) 一起作为 git 子模块使用。

使用以下命令添加子模块:

add_soem_submodule.sh
git submodule init
git submodule add https://github.com/OpenEtherCATsociety/SOEM

然后,在项目根目录中创建一个 list_slaves.cpp 文件,内容如下:

list_slaves.cpp
#include "ethercat.h"
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    if (argc <= 1) {
        printf("Usage: %s <network interface>\n", argv[0]);
        return 1;
    }
    char *ifname = argv[1];

    printf("Starting SOEM EtherCAT slave listing\n");

    // Initialize the SOEM library with the specified network interface
    if (ec_init(ifname)) {
        printf("EtherCAT master initialized on %s\n", ifname);

        // Perform an EtherCAT network scan
        if (ec_config_init(FALSE) > 0) {
            printf("%d slaves found and configured.\n", ec_slavecount);

            // Iterate through the slaves and print their information
            for (int i = 1; i <= ec_slavecount; i++) {
                printf("Slave %d: Name: %s, Output size: %d bits, Input size: %d bits, State: %d\n",
                       i,
                       ec_slave[i].name,
                       ec_slave[i].Obits,
                       ec_slave[i].Ibits,
                       ec_slave[i].state);
            }
        } else {
            printf("No slaves found.\n");
        }

        // Close the EtherCAT master
        ec_close();
    } else {
        printf("Failed to initialize EtherCAT master on %s\n", ifname);
    }

    return 0;
}

CMakelists.txt:

CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(soem_list_slaves)

# C++ Standard setzen
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(SOURCES "list_slaves.cpp")

file(GLOB_RECURSE SOEM_SOURCES
    # Third party
    "${CMAKE_CURRENT_SOURCE_DIR}/SOEM/soem/*.c"
    "${CMAKE_CURRENT_SOURCE_DIR}/SOEM/osal/linux/*.c"
    "${CMAKE_CURRENT_SOURCE_DIR}/SOEM/oshw/linux/*.c"
)

# Add the executable
add_executable(${PROJECT_NAME}
    ${SOURCES}
    ${SOEM_SOURCES}
)

target_include_directories(${PROJECT_NAME}
    PRIVATE
    "${CMAKE_CURRENT_SOURCE_DIR}/SOEM/soem"
    "${CMAKE_CURRENT_SOURCE_DIR}/SOEM/oshw"
    "${CMAKE_CURRENT_SOURCE_DIR}/SOEM/oshw/linux"
    "${CMAKE_CURRENT_SOURCE_DIR}/SOEM/osal/"
    "${CMAKE_CURRENT_SOURCE_DIR}/SOEM/osal/linux"
)

使用以下命令编译

build_soem.sh
cmake .
make

使用网络接口作为参数运行程序:

run_soem_list_slaves.sh
sudo ./soem_list_slaves eno1

示例输出:

soem_list_slaves_output.txt
Starting SOEM EtherCAT slave listing
EtherCAT master initialized on eno1
1 slaves found and configured.
Slave 1: Name: My EtherCAT slave, Output size: 0 bits, Input size: 0 bits, State: 1

Check out similar posts by category: EtherCAT, Networking