SOEM EtherCAT example: List all slaves
The following SOEM example lists all slaves.
It is intended to be used with SOEM (Simple Open EtherCAT Master) as a git submodule.
Add the submodule with:
git submodule init
git submodule add https://github.com/OpenEtherCATsociety/SOEM
Then, create a list_slaves.cpp
file in the root of your project with the following content:
#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:
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"
)
Compile using
cmake .
make
Run the program with the network interface as an argument:
sudo ./soem_list_slaves eno1
Example output:
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
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow