using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using System;
using System.Text;
using Alex;
/// <summary>
/// 串口通信
/// </summary>
public class SerialPortControl : MonoBehaviour
{
public string getPortName;
public int baudRate;
private Parity parity = Parity.None;
private int dataBits = 8;
private StopBits stopBits = StopBits.One;
SerialPort sp = null;
private string _data;
// Use this for initialization
void Start()
{
OpenPort(getPortName);
StartCoroutine(DataReceiveFunction());
}
/// <summary>
/// 串口信号控制
/// </summary>
private void PortSignalControl(string _str)
{
Debug.Log("收到串口信号:" + _str);
}
//打开串口
public void OpenPort(string DefaultPortName)
{
sp = new SerialPort(DefaultPortName, baudRate, parity, dataBits, stopBits);
sp.ReadTimeout = 10;
try
{
if (!sp.IsOpen)
{
sp.Open();
Debug.Log($"已成功开启{getPortName}端口...波特率{baudRate}");
}
}
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[256];//存储长度
int bytesToRead = 0;//记录获取的数据长度
while (true)
{
if (sp != null && sp.IsOpen)
{
try
{
//通过read函数获取串口数据
bytesToRead = sp.Read(dataBytes, 0, dataBytes.Length);
_data = dataBytes[0].ToString();
PortSignalControl(_data);
//串口数据已经被存入dataBytes中
}
catch (Exception ex)
{
}
}
yield return new WaitForSeconds(Time.deltaTime);
}
}
//发送一个字节
public void SendSerialPortData(string data)
{
if (sp.IsOpen)
{
Debug.Log("123123");
Byte[] bytes = StrToToHexByte(data);
sp.Write(bytes, 0, bytes.Length);
Debug.Log("321321");
}
}
private static byte[] StrToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
/// <summary>
/// 发送一个字符串
/// </summary>
public void SendString(string _dataStr)
{
SendSerialPortData(_dataStr);
}
private void OnApplicationQuit()
{
ClosePort();
}
private void OnDisable()
{
ClosePort();
}
}
感谢大家的观看,您的点赞和关注是我最大的动力
不定时更新知识点和干货呦~