如何将Arduino Nano 33 IoT陀螺仪数据接入Unity控制游戏挡板移动
实现步骤
1. Arduino端烧写数据发送代码
首先在Arduino IDE的库管理器中安装Arduino_LSM6DS3库(Nano 33 IoT内置IMU的官方驱动库),之后上传以下代码:
#include <Arduino_LSM6DS3.h> void setup() { Serial.begin(115200); while (!Serial); // 等待串口连接 if (!IMU.begin()) { Serial.println("IMU初始化失败"); while (1); } } void loop() { float gx, gy, gz; if (IMU.gyroscopeAvailable()) { IMU.readGyroscope(gx, gy, gz); // 按「X,Y,Z」格式输出数据,换行分隔 Serial.print(gx); Serial.print(","); Serial.print(gy); Serial.print(","); Serial.println(gz); } delay(10); // 控制数据发送频率 }
2. Unity项目基础配置
打开Unity编辑器,依次进入编辑 > 项目设置 > 播放器 > 其他设置,找到「Api兼容级别」选项,选择.NET Framework(部分旧版本Unity显示为.NET 4.x Equivalent),否则无法引用串口相关命名空间。
3. 修改Player控制代码
替换原有Player类代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO.Ports; using System; public class Player : MonoBehaviour { public float moveSpeed = 8.0f; public float topBounds = 8.3f; public float bottomBounds = -8.3f; public Vector2 startingPosition = new Vector2(-13.0f, 0.0f); [Space] [Header("Game")] [SerializeField] private Game game; [Space] [Header("Arduino串口配置")] public string portName = "COM3"; // 替换为你的Arduino实际COM端口 public int baudRate = 115200; // 和Arduino端波特率保持一致 public float gyroSensitivity = 2f; // 陀螺仪灵敏度,可按需调整 public bool useKeyboardFallback = true; // 串口异常时是否回退到键盘控制 private SerialPort serialPort; private float gyroInput = 0f; void Start() { transform.localPosition = startingPosition; // 初始化串口 try { serialPort = new SerialPort(portName, baudRate); serialPort.Open(); serialPort.ReadTimeout = 25; } catch (Exception e) { Debug.LogWarning($"串口打开失败:{e.Message},将自动回退到键盘控制"); useKeyboardFallback = true; } } void Update() { if (game.gameState == Game.GameState.Playing) { // 读取陀螺仪数据 if (serialPort != null && serialPort.IsOpen) { try { string data = serialPort.ReadLine(); string[] gyroValues = data.Split(','); if (gyroValues.Length == 3) { // 这里默认用gy的数值控制上下,如轴不对可换成gyroValues[0](gx)或gyroValues[2](gz) float.TryParse(gyroValues[1], out gyroInput); } } catch (TimeoutException) { // 读超时属于正常情况,忽略即可 } } CheckUserInput(); } } void CheckUserInput() { float moveDir = 0; if (!useKeyboardFallback) { // 用陀螺仪输入控制 moveDir = gyroInput * gyroSensitivity; } else { // 回退到键盘控制 if (Input.GetKey(KeyCode.UpArrow)) moveDir = 1; else if (Input.GetKey(KeyCode.DownArrow)) moveDir = -1; } // 位移计算和边界限制逻辑保持不变 Vector3 newPos = transform.localPosition + Vector3.up * moveDir * moveSpeed * Time.deltaTime; newPos.y = Mathf.Clamp(newPos.y, bottomBounds, topBounds); transform.localPosition = newPos; } void OnApplicationQuit() { // 退出时关闭串口,避免端口被占用 if (serialPort != null && serialPort.IsOpen) { serialPort.Close(); } } }
4. 运行前检查
- 打开Windows设备管理器,在「端口(COM和LPT)」分类下找到Arduino Nano 33 IoT对应的端口号,填入Unity Inspector中Player组件的
Port Name字段 - 确保Arduino IDE的串口监视器处于关闭状态,否则会占用串口导致Unity连接失败
- 如果控制方向相反,直接把
gyroSensitivity的数值改成负数即可 - 如果上下移动对应的倾斜轴不对,把代码中
gyroValues[1]换成gyroValues[0]或gyroValues[2]测试即可
内容的提问来源于stack exchange,提问作者PetiteFlamme31
相关产品推荐
相关产品推荐

