2. PLC控制LinuxCNC轴运动启动/停止
任务目标
通过PLC的数字输出信号控制LinuxCNC的轴运动启动与停止。PLC输出DO0作为启动信号,DO1作为停止信号,LinuxCNC通过hal_input组件读取这两个信号,并映射到轴运动控制逻辑中,实现外部PLC对轴运动的启停控制。
实现方案
使用LinuxCNC的HAL(硬件抽象层)机制,通过hal_input组件将PLC的数字输出信号接入HAL总线。启动信号触发轴运动使能,停止信号立即中止运动。本案例采用最小可复现实现:PLC侧信号用两个HAL手动开关模拟(sim_plc_start和sim_plc_stop),通过hal_input读取后,经逻辑处理连接到轴的enable和运动控制信号上。
环境依赖
- LinuxCNC 2.8或更高版本(已安装HAL库)
- 支持HAL的实时内核或模拟模式(
linuxcnc -s) - PLC数字输出模块(本案例用HAL软信号模拟,实际接入时替换为对应硬件驱动)
关键完整代码
创建HAL配置文件plc_axis_control.hal:
# 加载实时组件
loadrt trivkins
loadrt axis
loadrt hal_input
# 创建两个虚拟PLC数字输出(模拟PLC DO0/DO1)
newsig sim_plc_start bit
newsig sim_plc_stop bit
# 创建HAL输入引脚(实际PLC信号接入点)
# 格式: hal_input.<num>.bit.<name>
newinst hal_input.0 hal_input
setp hal_input.0.bit.plc_start 0
setp hal_input.0.bit.plc_stop 0
# 将模拟信号连接到hal_input引脚(实际使用时改为PLC硬件驱动)
setp hal_input.0.bit.plc_start 1
setp hal_input.0.bit.plc_stop 1
# 注意:上面两行仅为测试时手动置位,实际PLC接入时删除
# 连接hal_input输出到逻辑信号
net plc-start-cmd <= hal_input.0.bit.plc_start
net plc-stop-cmd <= hal_input.0.bit.plc_stop
# 轴运动控制逻辑
# 启动信号上升沿触发运动使能,停止信号立即禁用
loadrt and2
loadrt not2
loadrt edge
# 创建边沿检测组件
newinst edge_start edge
newinst edge_stop edge
setp edge_start.edge-type 0 ;# 上升沿触发
setp edge_stop.edge-type 1 ;# 下降沿触发(停止信号为高有效时用上升沿,此处用下降沿示例)
# 连接信号
net plc-start-cmd edge_start.in
net plc-stop-cmd edge_stop.in
# 运动使能逻辑:启动信号置位使能,停止信号复位使能
net axis-enable <= edge_start.out
net axis-enable <= edge_stop.out-inverted
# 将使能信号连接到轴0
net axis-enable => axis.0.enable
# 轴运动速度设置(测试用固定速度)
setp axis.0.velocity 10.0
# 加载运动控制器
loadrt motion
loadrt classicladder_rt
# 启动HAL线程
loadrt threads name1=servo-thread period1=1000000
addf motion-command-handler servo-thread
addf motion-controller servo-thread
addf hal_input.0.update servo-thread
addf edge_start.update servo-thread
addf edge_stop.update servo-thread
addf and2.0.update servo-thread
addf not2.0.update servo-thread
# 启动实时线程
start
运行与验证
- 启动LinuxCNC模拟模式:
linuxcnc -s,加载上述HAL文件。 - 在HAL终端中手动模拟PLC信号:
setp hal_input.0.bit.plc_start 1,观察轴0是否开始运动(axis.0.motion-type变为非零)。 - 置位停止信号:
setp hal_input.0.bit.plc_stop 1,确认轴运动立即停止。 - 通过
halscope或watch命令监控axis.0.enable和axis.0.velocity信号变化。
通过条件:启动信号置位后轴使能且速度达到设定值;停止信号置位后轴使能清零且速度归零,运动停止。
常见问题
- 若PLC信号为高电平有效,需调整
edge_stop的触发类型为上升沿(setp edge_stop.edge-type 0)。 - 实际PLC接入时,将
hal_input的引脚连接到对应硬件驱动(如hal_parport或现场总线驱动),删除模拟置位行。 - 轴运动前需确保已正确配置运动学(本案例使用trivkins)和轴限位。