Arduino无法连接Godot:串口权限与路径错误求助
Arduino与Godot串口连接问题求助
我尝试将Arduino控制器连接到Godot,实现敲击传感器触发时修改RichTextLabel的内容,但持续出现以下错误:
System.UnauthorizedAccessException: Access to the port '/dev/cu.USBmodem14201' is denied
System.IO.IOException: No such file or directory
所用代码
Godot C#代码
using Godot; using System; using System.IO.Ports; public partial class Arduino : Node2D { SerialPort serialPort; RichTextLabel text; // Called when the node enters the scene tree for the first time. public override void _Ready() { text = GetNode<RichTextLabel>("RichTextLabel"); serialPort = new SerialPort(); serialPort.PortName = "/dev/cu.USBmodem14201"; serialPort.BaudRate = 9600; serialPort.Open(); } // Called every frame. 'delta' is the elapsed time since the previous frame. public override void _Process(double delta) { if(!serialPort.IsOpen) return; string serialMessage = serialPort.ReadExisting(); if(serialMessage == "Knock recognized"){ text.Text = "Hello"; } } }
Arduino代码
int knock = 10; // Declaration of the sensor input pin int value; // Temporary variable void setup () { pinMode(knock, INPUT); // Initialization sensor pin Serial.begin(9600); // Initialization of the serial monitor Serial.println("KY-031 Knock test"); } void loop () { // The current signal at the sensor is read out. value = digitalRead(knock); // If a signal could be detected, this is printed on the serial monitor. if (value == LOW) { Serial.println("Knock recognized"); delay(200); // 200 ms break } }
解决建议
1. 确认串口路径准确性
- 打开Arduino IDE,通过工具 > 端口查看Arduino实际占用的端口,确保Godot代码中的
PortName与该路径完全匹配(注意端口编号、大小写,可能是/dev/cu.usbmodemXXXX或/dev/tty.usbmodemXXXX)。 - 若端口不存在,检查USB连接是否正常,尝试更换USB接口或重启设备。
2. 修复串口权限问题(macOS/Linux)
- macOS:终端执行命令
sudo chmod 666 /dev/cu.USBmodem14201(替换为你的实际端口路径),授予当前用户串口读写权限。 - Linux:将用户加入
dialout组,执行sudo usermod -aG dialout $USER,完成后重启系统或重新登录。
3. 释放被占用的串口
- 关闭Arduino IDE的串口监视器,同一串口不能被多个程序同时占用。
- 检查是否有其他串口工具(如Screen、Minicom)正在使用该端口,关闭后再运行Godot项目。
4. 代码优化
- 添加异常捕获,避免程序因串口连接失败直接崩溃:
try { serialPort.Open(); GD.Print("串口连接成功"); } catch (Exception e) { GD.PrintErr("串口打开失败: ", e.Message); }
- 读取串口数据时去除空白字符(如换行符),避免匹配失败:
string serialMessage = serialPort.ReadExisting().Trim(); if(serialMessage == "Knock recognized"){ text.Text = "Hello"; }
内容的提问来源于stack exchange,提问作者Meloen
相关产品推荐
相关产品推荐

