You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python脚本向Arduino(GRBL)串口监视器发送G-code指令

使用Python脚本向搭载GRBL框架的Arduino发送G-code指令

本文介绍如何通过Python脚本向搭载GRBL框架的Arduino串口监视器发送G-code指令,以下是实现代码:

import serial
import time

# 定义串口端口和波特率
serial_port = "COM5"  # 请修改为你的设备串口
baud_rate = 115200  # 请修改为匹配设备的波特率

# 预定义G-code指令列表
coms = [
    "G90",
    "G21",
    "G92 X0 Y0",
    "G1 F1000",
    "M5 S90",
    "G4 P0.2",
    "G1 F1000",
    "G1 X20",
    "G1 Y20",
    "G1 X0",
    "G1 Y0",
    "M3",
]

# 打开串口
ser = serial.Serial(serial_port, baud_rate, timeout=1)

try:
    if ser.is_open:
        print(f"串口 {serial_port} 已成功打开。")
        
        while True:
            # 读取串口数据
            data = ser.readline().decode().strip()
            if data:
                print("收到数据:", data)

            user_input = input("输入指令(X解锁系统,H执行回零,输入其他内容发送预定义G-code序列):").strip().upper()

            if user_input == "X":
                print("正在解锁系统")
                ser.write(b"$X")
            elif user_input == "H":
                print("启动回零循环")
                ser.write(b"$H")
            else:
                print("正在发送G-code指令...")
                for command in coms:
                    print("发送指令:", command)
                    ser.write(command.encode())
                    time.sleep(1)  # 可根据需要调整指令间延迟

            # 等待CNC设备响应
            grbl_out = ser.readline().decode().strip()
            print("设备响应:", grbl_out)

except KeyboardInterrupt:
    print("检测到键盘中断,正在退出...")

finally:
    # 关闭串口
    if ser.is_open:
        ser.close()
        print("串口已关闭。")

脚本说明

该脚本支持通过串口与搭载GRBL框架的Arduino CNC控制器通信,提供命令行交互界面发送G-code指令。

核心特性

  • 建立与指定COM口的串口连接
  • 读取并显示串口接收的设备数据
  • 支持三种交互指令:
    • 输入X:解锁CNC系统
    • 输入H:启动设备回零循环
    • 输入其他内容:发送预定义的G-code指令序列
  • 按顺序发送G-code指令,可自定义指令间延迟
  • 实时显示CNC设备的响应信息

脚本采用交互式设计,在指令发送和设备响应全过程中向用户反馈状态。

使用的硬件组件

  • Arduino Uno开发板
  • CNC shield V3(protneer)扩展板
  • Nema 17步进电机
  • SG90伺服电机
  • A4988步进电机驱动器
  • GRBL框架固件

内容的提问来源于stack exchange,提问作者Shahal T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 06:52:34