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();//关闭串口
    }

}

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

  • 1
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值