# 如何用 MATLAB 经 Arduino 发送 G132 驱动伺服

> 原文链接：https://robotics.hellobike.com/pitfalls/2017-09-18-robotics-se-12583
> 频道：pitfalls | 更新日期：2017-09-18 | 标签：auto, stackexchange, arduino, matlab, servomotor
> 核心摘要：MATLAB 串口先分段建连并用 fprintf 发送，Arduino Mega 解析数值后拼接 G 命令转发给电机驱动。

# 如何用 MATLAB 经 Arduino 发送 G132 驱动伺服

::: v-pre
> 本文由 AI 根据公开内容整理，可能有误，请以原文为准：[Driving Rhino DC servo motor using Arduino through commands sending from MATLAB](https://robotics.stackexchange.com/questions/12583/driving-rhino-dc-servo-motor-using-arduino-through-commands-sending-from-matlab)（Robotics Stack Exchange #12583）

**状态**：已解决

## 问题

手动在终端输入 `G400`、`R821` 可驱动电机，但希望将 MATLAB 计算出的角度自动转换为计数值并发送给电机，例如 26.4° 对应 132 counts，即发送 `G132`。

## 环境

嵌入式控制器 / 串口通信

## 解决办法

1. 在 Arduino Mega 上用 `Serial` 接收 MATLAB 数据，用 `Serial1` 连接电机驱动；在循环中用 `Serial.parseFloat()` 读取 `d1`、`d2`、`d3`、`d4`。
2. 单电机测试时将 `d1` 拼成 `stringG1 = "G" + String(d1)`，再用 `Serial1.println(stringG1)` 发送给驱动。
3. MATLAB 先创建并打开串口：`s = serial('COM9','BaudRate',9600,'Terminator','LF')`，设置 `s.timeout = 1`，执行 `fopen(s)`；失败时先 `delete(s)` 再 `fopen(s)`。
4. 先单独运行建连段，连接建立后反复运行 `angle = [250,200,50,120]` 和 `fprintf(s,'%d\n',angle)` 发送值；最后用 `fclose(s)` 并 `delete(inst…

原问题作者：Naseeb Gill；采纳答案作者：Naseeb Gill。原内容依 CC BY-SA 4.0 授权，本页摘要同样依 CC BY-SA 4.0 授权。
:::

## 原始参考来源 (Sources)

- [Robotics Stack Exchange #12583：Driving Rhino DC servo motor using Arduino through commands sending from MATLAB](https://robotics.stackexchange.com/questions/12583/driving-rhino-dc-servo-motor-using-arduino-through-commands-sending-from-matlab)