项目用到串口通信,本文综合了两位博主的代码块,实现的Unity2018.3环境下的串口热插拔16进制通信
。
串口热插拔zhoudapeng01
16进制通信Rick__
里边涉及到一些逻辑判断,新手直接Ctrl+C V的话,也无法运行,核心代码如下:
热插拔 -读取当前环境下串口占用:
private string GetPortName()
{
try
{
Process processGetPortName = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo(Environment.CurrentDirectory+"\\GetPortNum.exe");
processGetPortName.StartInfo = startInfo;
processGetPortName.StartInfo.UseShellExecute = false;
processGetPortName.StartInfo.RedirectStandardOutput = true;
processGetPortName.Start();
string output = processGetPortName.StandardOutput.ReadToEnd();
if (int.Parse(output) > 10)
output = "\\\\?\\" + "COM" + output;
else
output = "COM" + output;
return output;
}
catch (Exception ex)
{
UnityEngine.Debug.Log("出错原因:" + ex.Message);
return "";
}
}
串口接收16进制代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using System.Threading;
using System.IO;
using UnityEngine.Video;
using System;
using System.Text;
public class PortTestScript : MonoBehaviour
{
public string portName = " ";
public int baudrate = 9600;
public Parity parite = Parity.None;
public int dataBits = 8;
public StopBits stopbits = StopBits.One;
SerialPort port;
Thread portRev, portDeal;
Queue <string> dataQueue;
string outStr = string.Empty;
void Start ()
{
//本地路径
string fileAddress = System.IO.Path.Combine (Application.streamingAssetsPath, "PortNameConfig.txt");
FileInfo fInfo0 = new FileInfo (fileAddress);
string s = "";
if (fInfo0.Exists) {
StreamReader r = new StreamReader (fileAddress);
s = r.ReadToEnd ();
portName = s;
dataQueue = new Queue<string> ();
port = new SerialPort (portName, baudrate, parite, dataBits, stopbits);
port.ReadTimeout = 400;
try {
port.Open ();
Debug.Log ("串口打开成功!");
portRev = new Thread (PortReceivedThread);
portRev.IsBackground = true;
portRev.Start ();
portDeal = new Thread (DealData);
portDeal.Start ();
} catch (System.Exception ex) {
Debug.Log (ex.Message);
}
}
}
//接收数据
void PortReceivedThread ()
{
try {
byte[] buf = new byte[1];
string resStr = string.Empty;
if (port.IsOpen) {
port.Read (buf, 0, 1);
}
if (buf.Length == 0) {
return;
}
if (buf != null) {
for (int i = 0; i < buf.Length; i++) {
// resStr += ASCIIEncoding.UTF8.GetString (buf);
resStr += buf [i].ToString ("X2") + " ";
// resStr += Encoding.UTF8.GetString (buf);
dataQueue.Enqueue (resStr);
resStr += resStr;
// print (resStr);
}
}
} catch (System.Exception ex) {
// Debug.Log (ex.Message);
}
}
string message = " ";
//处理
void DealData ()
{
while (dataQueue.Count != 0) {
for (int i = 0; i < dataQueue.Count; i++) {
outStr += dataQueue.Dequeue ();
if (outStr.Length == 24) {
Debug.Log (outStr);
message = outStr;
outStr = string.Empty;
}
}
}
}
public GameObject _shotctl;
/// <summary>
/// 传参数
/// </summary>
/// <param name="message"></param>
void GetTheMessage (string message)
{
//传参数给 _shotctl这个游戏物体
_shotctl.SendMessage ("GetShotMessage", message);
}
void SendData (byte[]msg)
{
//这里要检测一下msg
if (port.IsOpen) {
port.Write (msg, 0, msg.Length);
}
}
string Info = " ";
// Update is called once per frame
void Update ()
{
if (port.IsOpen) {
if (!portRev.IsAlive) {
portRev = new Thread (PortReceivedThread);
portRev.IsBackground = true;
portRev.Start ();
}
if (!portDeal.IsAlive) {
portDeal = new Thread (DealData);
portDeal.Start ();
}
}
if (Info != message) {
GetTheMessage (message);
Info = message = " ";
}
}
void OnApplicationQuit ()
{
Debug.Log ("退出!");
if (port.IsOpen) {
if (portRev.IsAlive) {
portRev.Abort ();
}
if (portDeal.IsAlive) {
portDeal.Abort ();
}
}
port.Close ();
}
}
通过串口热插拔代码加上自己的逻辑判断,可以实现打开指定COM口,然后即可实现16进制通信。## Unity 串口热插拔 及16进制通信