using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using System;
using System.Threading;
using UnityEngine.UI;
public class PortManager {
private SerialPort sp = null;//端口
bool isActive = false;
private Thread athread;
public Action<string> ReadDataEvent;
object lockd = new object();
/// <summary>
/// 初始化端口
/// </summary>
public void InitPort(string portName,int baudRate) {
isActive = true;
sp = new SerialPort("\\\\.\\" + portName, baudRate);
}
/// <summary>
/// 打开端口
/// </summary>
public void OpenPort() {
try {
sp.Open();
} catch( Exception ex ) {
Debug.Log(ex.Message);
}
}
/// <summary>
/// 关闭端口
/// </summary>
public void ClosePort() {
try {
sp.Close();
} catch( Exception ex ) {
Debug.Log(ex.Message);
}
}
/// <summary>
/// 获取所有端口
/// </summary>
/// <returns></returns>
public string[] GetAllPorts() {
return SerialPort.GetPortNames();
}
/// <summary>
/// 开始读取数据
/// </summary>
public void StartReadData() {
athread = new Thread(new ThreadStart(GoThread));
athread.IsBackground = true;
athread.Start();
}
void GoThread() {
while( isActive ) {
lock( lockd ) {
ReadPortData();
}
Thread.Sleep(10);
}
}
private void ReadPortData() {
if( sp != null && sp.IsOpen ) {
try {
string portValue = sp.ReadLine();
if( !string.IsNullOrEmpty(portValue) && ReadDataEvent != null ) {
ReadDataEvent(portValue);
}
} catch( Exception ex ) {
Debug.Log(ex.Message);
}
} else {
Debug.LogError("请检查端口设置!");
}
}
}
Unity获取串口数据
最新推荐文章于 2024-04-06 16:16:44 发布