Unity Arduino 串口通信

该文介绍如何使用Unity控制Arduino设备,通过串口通信实现开灯、关灯功能。在Unity端,点击按钮发送‘a’或‘b’命令,Arduino接收到后改变PIN_KEY的状态。同时,Arduino定时发送‘a’和‘o’,Unity接收到后改变游戏对象的颜色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Unity发送消息Arduino接收消息 通过串口通信

Arduino端

#include <Arduino.h>

#define PIN_KEY 5
uint item;

void setup() {
    item = 0;
    Serial.begin(115200);
    pinMode(PIN_KEY, OUTPUT);  
}

void loop() {
    if(Serial.available()>0)
    {
        item = Serial.read();        
    }
    if(item == 'a')
    {
        digitalWrite(PIN_KEY,HIGH); 
    }
    if(item == 'b')
    {
        digitalWrite(PIN_KEY,LOW); 
    }
}

Unity端

public class Test : MonoBehaviour
{
    SerialPort port = new SerialPort("COM4", 115200);

    public Button Btn_Open;
    public Button Btn_Close;

    private void Start()
    {
        port.Open();
        port.ReadTimeout = 1;

        Btn_Open.onClick.AddListener(() => {
            port.WriteLine("a");
        });

        Btn_Close.onClick.AddListener(() => {
            port.WriteLine("b");
        });
    }
}

实现串口通信,点击开灯按钮,灯亮。关灯按钮,灯灭。

二、Unity接收消息Arduino发送消息 通过串口通信

Arduino端

#include <Arduino.h>

void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.println("a");
    delay(1000);
    Serial.println("o");
    delay(1000);
}

Unity端

1.导入Ardity插件(在Unity商城中找)

2.打开读写实例场景

 3.添加读写的实例脚本

 4.

/**
 * Ardity (Serial Communication for Arduino + Unity)
 * Author: Daniel Wilches <dwilches@gmail.com>
 *
 * This work is released under the Creative Commons Attributions license.
 * https://creativecommons.org/licenses/by/2.0/
 */

using UnityEngine;
using System.Collections;

/**
 * Sample for reading using polling by yourself, and writing too.
 */
public class SampleUserPolling_ReadWrite : MonoBehaviour
{
    public MeshRenderer Cube;
    public SerialController serialController;

    // Initialization
    void Start()
    {
        serialController = GameObject.Find("SerialController").GetComponent<SerialController>();

        Debug.Log("Press A or Z to execute some actions");
    }

    // Executed each frame
    void Update()
    {
        //---------------------------------------------------------------------
        // Send data
        //---------------------------------------------------------------------

        // If you press one of these keys send it to the serial device. A
        // sample serial device that accepts this input is given in the README.
        if (Input.GetKeyDown(KeyCode.N))
        {
            Debug.Log("Sending n");
            serialController.SendSerialMessage("n");
        }

        if (Input.GetKeyDown(KeyCode.M))
        {
            Debug.Log("Sending m");
            serialController.SendSerialMessage("m");
        }


        //---------------------------------------------------------------------
        // Receive data
        //---------------------------------------------------------------------

        string message = serialController.ReadSerialMessage();

        if (message == null)
            return;

        // Check if the message is plain data or a connect/disconnect event.
        if (ReferenceEquals(message, SerialController.SERIAL_DEVICE_CONNECTED))
            Debug.Log("Connection established");
        else if (ReferenceEquals(message, SerialController.SERIAL_DEVICE_DISCONNECTED))
            Debug.Log("Connection attempt failed or disconnection detected");
        else 
        {
            if (message.Equals("a")) 
            {
                Cube.material.color = Color.red;
            }
            if (message.Equals("o"))
            {
                Cube.material.color = Color.white;
            }
            Debug.Log("Message arrived: " + message);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值