using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO.Ports;
public class PortManager : MonoBehaviour
{
string getPortName;
int baudRate = 9600;
private Parity parity = Parity.None;
private int dataBits = 8;
private StopBits stopBits = StopBits.One;
SerialPort sp = null;
private string _data;
private string testString;
// Use this for initialization
void Start()
{
getPortName = "COM3";
testString = "b";
OpenPort(getPortName);
StartCoroutine(DataReceiveFunction());
}
/// <summary>
/// 串口信号控制
/// </summary>
private void PortSignalControl()
{
if (_data == System.Text.Encoding.ASCII.GetBytes(testString)[0].ToString())
{
Debug.Log("收到串口信号" + testString);
}
}
//打开串口
public void OpenPort(string DefaultPortName)
{
sp = new SerialPort(DefaultPortName, baudRate, parity, dataBits, stopBits);
sp.ReadTimeout = 10;
try
{
if (!sp.IsOpen)
{
sp.Open();
}
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
//关闭串口
public void ClosePort()
{
try
{
sp.Close();
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
IEnumerator DataReceiveFunction()
{
byte[] dataBytes = new byte[128];//存储长度
int bytesToRead = 0;//记录获取的数据长度
while (true)
{
if (sp != null && sp.IsOpen)
{
try
{
//通过read函数获取串口数据
bytesToRead = sp.Read(dataBytes, 0, dataBytes.Length);
_data = dataBytes[0].ToString();
print(_data);
PortSignalControl();
//串口数据已经被存入dataBytes中
}
catch (Exception ex)
{
}
}
yield return new WaitForSeconds(Time.deltaTime);
}
}
//发送一个字节
public void SendSerialPortData(string data)
{
if (sp.IsOpen)
{
sp.WriteLine(data);
}
}
/// <summary>
/// 发送一个字符串
/// </summary>
public void SendString()
{
SendSerialPortData("a");
}
private void OnApplicationQuit()
{
ClosePort();
}
private void OnDisable()
{
ClosePort();
}
}
unity串口通信
最新推荐文章于 2023-10-20 11:45:01 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)