一、简 介

1.首先Unity是支持串口通信的,只不过Unity采用的是Mono .NET 2.0。之前版本对COM支持不是很好,所以导致Unity在串口通信方面有些问题。

小编用的版本是2018.4.0

首先想使用Unity开发串口通信,必须要做的 一点就是 要使用Mono.NET 2.0/4.0/其他

如下图:

android unity串口 unity 串口接收_串口通信


不修改的话是不能进行串口开发的,可能Unity不想让大家用来干些别的事吧 (ˉ▽ ̄~)

2.修改完之后下面是代码环节,简单通俗易懂

二、功能

1.首先需要获取一些数据,串口号啊什么的,必须要有的。
public static string portName;//串口号
    public static int baudRate;//波特率
    public static Parity parity;//校验位
    public static int dataBit;//数据位
    public static StopBits stopBit;//停止位
2.然后就需要连接串口
/// <summary>
    /// 打开端口
    /// </summary>
    public static void OpenPort()
    {
        sp = new SerialPort(portName, baudRate, parity, dataBit, stopBit);
        sp.ReadTimeout = 1000;
        try
        {
            sp.Open();
            Debug.Log("打开端口成功");
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
        }
    }
3.连接成功后,就需要交互了
/// <summary>
    /// 发送数据
    /// </summary>
    /// <param name="dataStr"></param>
    public static void SendData(byte[] dataStr)
    {
        sp.Write(dataStr, 0, dataStr.Length);
        Debug.LogWarning("发送成功");
    }
/// <summary>
    /// 接收端口数据
    /// </summary>
    public void DataReceiveFun()
    {
        while (true)
        {
            if (sp != null && sp.IsOpen)
            {
                try
                {
                    bytes = sp.Read(buffer, 0, buffer.Length);
                    sp.DiscardOutBuffer();
                    if (bytes == 0)
                    {
                        continue;
                    }
                    else
                    {
                        for (int i = 0; i < buffer.Length; i++)
                        {
                            Debug.Log(buffer[i].ToString("x8"));
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.Log(e);
                }
            }
            Thread.Sleep(500);
        }
    }

三、附上一些其他便捷功能

1.编写过程中会发现串口的消息进制不是很方便,16进制就需要转换成我们熟知的10进制或者其他一些方便的 (ˉ▽ ̄~) 先来
//十进制转二进制

Console.WriteLine(Convert.ToString(69, 2));

//十进制转八进制

Console.WriteLine(Convert.ToString(69, 8));

//十进制转十六进制

Console.WriteLine(Convert.ToString(69, 16));

//二进制转十进制

Console.WriteLine(Convert.ToInt32("100111101", 2));

//八进制转十进制

Console.WriteLine(Convert.ToInt32("76", 8));

//16进制转换10进制

Console.WriteLine(Convert.ToInt32("FF", 16));
2.细心的小伙伴会发现 发送消息那里是不是有点难搞哦 (ˉ▽ ̄~) 我来了,是不是参数换成字符串会通俗易懂很多呢(ˉ▽ ̄~)
/// <summary>
    /// 字符串转字节流
    /// </summary>
    /// <param name="hexStr"></param>
    /// <returns></returns>
    public static byte[] HexStringToBytes(string hexStr)
    {
        if (string.IsNullOrEmpty(hexStr))
        {
            return new byte[0];
        }
        if (hexStr.StartsWith("0x"))
        {
            hexStr = hexStr.Remove(0, 2);
        }
        var count = hexStr.Length;
        var byteCount = count / 2;
        var result = new byte[byteCount];
        for (int ii = 0; ii < byteCount; ++ii)
        {
            var tempBytes = Byte.Parse(hexStr.Substring(2 * ii, 2), System.Globalization.NumberStyles.HexNumber);
            result[ii] = tempBytes;
        }
        return result;
    }
     //第二种 常用转换方式 推荐
    public static byte[] Convert16(string strText)
    {
        strText = strText.Replace(" ", "");
        byte[] bText = new byte[strText.Length / 2];
        for (int i = 0; i < strText.Length / 2; i++)
        {
            bText[i] = Convert.ToByte(Convert.ToInt32(strText.Substring(i * 2, 2), 16));
        }
        return bText;
    }

推荐使用第二种转换方式,多次测试可行很稳定。
拿走不谢,直接转换成字符串, 有了转字符串,肯定要有再转回来的方法,对不对

/// <summary>
    /// 字节流转字符串
    /// </summary>
    /// <param name="bytes"></param>
    /// <returns></returns>
    public static string BytesTohexString(byte[] bytes)
    {
        if (bytes == null || bytes.Length < 1)
        {
            return string.Empty;
        }

        var count = bytes.Length;

        var cache = new StringBuilder();
        cache.Append("0x");
        for (int ii = 0; ii < count; ++ii)
        {
            var tempHex = Convert.ToString(bytes[ii], 16).ToUpper();
            cache.Append(tempHex.Length == 1 ? "0" + tempHex : tempHex);
        }

        return cache.ToString();
    }

这个就用处不大了,大家斟酌使用~~

目前小编能想到的方便开发的小功能就这么多,欢迎留言告知~后期会跟新(ˉ▽ ̄~)
下面为大家附上完整代码一张 客官请~~~~
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using System.Threading;
using System;
using System.Text;
/// <summary>
/// 串口通信
/// </summary>
public class SerialPortControl
{
    public static string portName;//串口号
    public static int baudRate;//波特率
    public static Parity parity;//校验位
    public static int dataBit;//数据位
    public static StopBits stopBit;//停止位
    static SerialPort sp = new SerialPort();
    /// <summary>
    /// 串口号
    /// </summary>
    /// <param name="portname"></param>
    /// <returns></returns>
    public static string PortName(string portname)
    {
        portName = portname;
        return portName;
    }
    /// <summary>
    /// 波特率
    /// </summary>
    /// <param name="baud"></param>
    /// <returns></returns>
    public static int BauRate(int baud)
    {
        baudRate = baud;
        return baudRate;
    }
    /// <summary>
    /// 校验位
    /// </summary>
    /// <param name="paritys"></param>
    /// <returns></returns>
    public static Parity Paritys(Parity paritys)
    {
        parity = paritys;
        return parity;
    }
    /// <summary>
    /// 数据位
    /// </summary>
    /// <param name="dataBits"></param>
    /// <returns></returns>
    public static int DataBits(int dataBits)
    {
        dataBit = dataBits;
        return dataBit;
    }
    /// <summary>
    /// 停止位
    /// </summary>
    /// <param name="stopBits"></param>
    /// <returns></returns>
    public static StopBits StopBitss(StopBits stopBits)
    {
        stopBit = stopBits;
        return stopBit;
    }
    /// <summary>
    /// 字节流转字符串
    /// </summary>
    /// <param name="bytes"></param>
    /// <returns></returns>
    public static string BytesTohexString(byte[] bytes)
    {
        if (bytes == null || bytes.Length < 1)
        {
            return string.Empty;
        }

        var count = bytes.Length;

        var cache = new StringBuilder();
        cache.Append("0x");
        for (int ii = 0; ii < count; ++ii)
        {
            var tempHex = Convert.ToString(bytes[ii], 16).ToUpper();
            cache.Append(tempHex.Length == 1 ? "0" + tempHex : tempHex);
        }

        return cache.ToString();
    }
    /// <summary>
    /// 字符串转字节流
    /// </summary>
    /// <param name="hexStr"></param>
    /// <returns></returns>
    public static byte[] HexStringToBytes(string hexStr)
    {
        if (string.IsNullOrEmpty(hexStr))
        {
            return new byte[0];
        }
        if (hexStr.StartsWith("0x"))
        {
            hexStr = hexStr.Remove(0, 2);
        }
        var count = hexStr.Length;
        var byteCount = count / 2;
        var result = new byte[byteCount];
        for (int ii = 0; ii < byteCount; ++ii)
        {
            var tempBytes = Byte.Parse(hexStr.Substring(2 * ii, 2), System.Globalization.NumberStyles.HexNumber);
            result[ii] = tempBytes;
        }
        return result;
    }
    
    //字符串转字节流 推荐======
    public static byte[] Convert16(string strText)
    {
        strText = strText.Replace(" ", "");
        byte[] bText = new byte[strText.Length / 2];
        for (int i = 0; i < strText.Length / 2; i++)
        {
            bText[i] = Convert.ToByte(Convert.ToInt32(strText.Substring(i * 2, 2), 16));
        }
        return bText;
    }
    /// <summary>
    /// 打开端口
    /// </summary>
    public static void OpenPort()
    {
        sp = new SerialPort(portName, baudRate, parity, dataBit, stopBit);
        sp.ReadTimeout = 1000;
        try
        {
            sp.Open();

            Debug.Log("打开端口成功");
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
        }
    }
    /// <summary>
    /// 关闭端口
    /// </summary>
    public static void ClosePort()
    {
        try
        {
            sp.Close();
            sp.Dispose();
            Debug.Log("关闭端口");
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
        }
    }

    byte[] buffer = new byte[5];
    int bytes = 0;

    /// <summary>
    /// 接收端口数据
    /// </summary>
    public void DataReceiveFun()
    {
        while (true)
        {
            if (sp != null && sp.IsOpen)
            {
                try
                {
                    bytes = sp.Read(buffer, 0, buffer.Length);
                    sp.DiscardOutBuffer();
                    if (bytes == 0)
                    {
                        continue;
                    }
                    else
                    {
                        for (int i = 0; i < buffer.Length; i++)
                        {
                            Debug.Log(buffer[i].ToString("x8"));
                        }

                    }
                }
                catch (Exception e)
                {
                    Debug.Log(e);
                }
            }
            Thread.Sleep(500);
        }
    }
    /// <summary>
    /// 发送数据
    /// </summary>
    /// <param name="dataStr"></param>
    public static void SendData(byte[] dataStr)
    {
        sp.Write(dataStr, 0, dataStr.Length);
        Debug.LogWarning("发送成功");
    }
}