unity3d 讀取串列埠

西北逍遥發表於2024-07-12

unity3d 讀取串列埠

using System.IO.Ports;
using UnityEngine;

public class SerialCommunication : MonoBehaviour
{
    SerialPort mySerialPort = new SerialPort("COM3"); // 更改為你的串列埠名

    void Start()
    {
        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        mySerialPort.Open();
    }

    private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadLine();
        Debug.Log("Data Received:" + indata);
    }

    void OnDestroy()
    {
        if (mySerialPort.IsOpen)
        {
            mySerialPort.Close();
        }
    }
}

#######################

相關文章