SOEM EtherCAT example: How to read String object at specific subindex

The following example builds on our previous post SOEM EtherCAT example: List all slaves.

It lists a single object, 0x2019, subindex 0x06, which is listed as STRING(32) in the user manual.

char stringBuffer[32];
memset(stringBuffer, 0, sizeof(stringBuffer));

int psize = 32;
int result = ec_SDOread(i, 0x2019, 0x06, FALSE, &psize, &stringBuffer, EC_TIMEOUTRXM);
if (result > 0) {
  printf("PDO 0x2019:06 String: %s\n", stringBuffer);
} else {
  printf("Fehler beim Lesen von PDO 0x2019:06\n");
}

Full example

See SOEM EtherCAT example: List all slaves for the CMake configurationh

#include "ethercat.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.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);
                
                // Buffer für den String (32 Bytes)
                char stringBuffer[32];
                memset(stringBuffer, 0, sizeof(stringBuffer));
                
                // SDO lesen
                int psize = 32;
                int result = ec_SDOread(i, 0x2019, 0x06, FALSE, &psize, &stringBuffer, EC_TIMEOUTRXM);
                if (result > 0) {
                    printf("PDO 0x2019:06 String: %s\n", stringBuffer);
                } else {
                    printf("Fehler beim Lesen von PDO 0x2019:06\n");
                }
            }
        } 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;
}