Unity读取串口数据

读取串口数据的过程其实就跟你读取文件操作IO时的过程差不多:

首先要使用using System.IO.Ports;时需要先将
这里写图片描述
改为
这里写图片描述

具体操作: Edit -> Project Settings -> Player -> Other Settings -> Api Compatibility Level

具体代码

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Text.RegularExpressions;
using System.Text;
using System;

public class Mpu6050 : MonoBehaviour {

    public GameObject target;//目标操作物体
    private SerialPort sp;
    private Thread recvThread;//线程
    float x, y, z, buttonState = 0, sensorValue = 0;//存放欧拉角  

    // Use this for initialization   
    void Start()
    {
        sp = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.One);
        //串口初始化  
        if (!sp.IsOpen)
        {
            sp.Open();
        }
        recvThread = new Thread(ReceiveData); //该线程用于接收串口数据  
        recvThread.Start();
    }
    void Update()
    {
        //...
    }

    private void ReceiveData()
    {
        try
        {
            string s = "";
            //以行的模式读取串口数据
            while ((s = sp.ReadLine()) != null)
            {
                print(s); //打印读取到的每一行数据
            }
        }
        catch (Exception ex)
        {
            Debug.Log(ex);
        }
    }

    void OnApplicationQuit()
    {
        sp.Close();//关闭串口
    }

}

当然使用此代码时需要注意你串口数据需要以一行一行的形式进行传输。

猜你喜欢

转载自blog.csdn.net/l1336037686/article/details/80160454
今日推荐