SOEM-EtherCAT-Beispiel: Alle Slaves auflisten

Das folgende SOEM-Beispiel listet alle Slaves auf.

Es ist dafür gedacht, mit SOEM (Simple Open EtherCAT Master) als Git-Submodul verwendet zu werden.

Fügen Sie das Submodul hinzu mit:

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

Erstellen Sie dann eine list_slaves.cpp-Datei im Root Ihres Projekts mit folgendem Inhalt:

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"
)

Kompilieren mit

build_soem.sh
cmake .
make

Führen Sie das Programm mit der Netzwerkschnittstelle als Argument aus:

run_soem_list_slaves.sh
sudo ./soem_list_slaves eno1

Beispiel-Ausgabe:

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