参考链接
SOEM v1.4.0 tutorial.txt File Reference
SOEM Github链接
编译源码
下载SOEM源码,按照源码中的readme编译生成SOEM库文件及测试文件
make 编译生成相关文件
继续执行安装命令:
make install
生成安装文件目录
将上述生成的安装文件拷贝到/usr目录下对应的lib、include、bin目录下即可使用
查看IO寄存器地址
在linux终端里输入下面的命令
$ sudo ./slaveinfo enp2s0 -map
注意enp2s0为已经连接EtherCAT设备的网卡名称
设备描述信息
编写测试例程
该代码实现了输入按键检测并对应输出不同的LED状态
注意:
- 在netcard_name变量中更改已经连接EtherCAT设备的网卡名称
- ec_slave[0].outputs中的地址根据自己的设备地址进行更改
main.c
#include <stdio.h>
#include <unistd.h>
#include "ethercattype.h"
#include "nicdrv.h"
#include "ethercatmain.h"
#include "ethercatconfig.h"
char IOmap[4096];
void slave2op(int i){
ec_slave[i].state = EC_STATE_OPERATIONAL;
ec_send_processdata();
ec_receive_processdata(EC_TIMEOUTRET);
ec_writestate(0);
}
void simpletest(char *ifname){
int8_t ret = 0;
int i,j=0;
if(ec_init(ifname)){
printf("start ethernet at %s\n",ifname);
if ( ec_config_init(FALSE) > 0 ){
printf("found %d slave on the bus\n",ec_slavecount);
ec_config_map(&IOmap);
for(i=0;i<ec_slavecount;i++){
printf("slave%d to op\n", i);
slave2op(i);
}
if(ec_slave[j].state == EC_STATE_OPERATIONAL){
while(1){
ret = ec_slave[0].outputs[0x0006];ec_receive_processdata(EC_TIMEOUTRET);
if(0 == ((ret & 0x80) >> 7)){
ec_slave[0].outputs[0x0000] = 0xAA;
}
if(0 == ((ret & 0x40) >> 6)){
ec_slave[0].outputs[0x0000] = 0x55;
}
/* send one valid process data to make outputs in slaves happy*/
ec_send_processdata();ec_receive_processdata(EC_TIMEOUTRET);
}
}
else{
slave2op(j);
printf("slave again to op\n");
}
}
else{
printf("no slave on the bus\n");
}
}
else{
printf("no ethernet card\n");
}
}
char * netcard_name="enp2s0";
int main(int argc, char *argv[])
{
printf("SOEM 1.4.0 IO read/write test!\n");
simpletest(netcard_name);
printf("The end\n");
return (0);
}
CmakeLists
cmake_minimum_required(VERSION 3.0)
project(EtherCAT)
set(CMAKE_CXX_STANDARD 17)
include_directories(/usr/include/soem)
add_executable(EtherCAT main.cpp)
target_link_libraries(EtherCAT soem pthread)