unity3d 读取串口

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();
        }
    }
}

 

 

 

 

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

posted @ 2024-07-12 00:27  西北逍遥  阅读(32)  评论(0编辑  收藏  举报