⭐ Unity 串口通信脚本

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();
	}
}

感谢大家的观看,您的点赞和关注是我最大的动力

不定时更新知识点和干货呦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值