欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

串口通信

程序员文章站 2022-06-18 11:27:13
...

首先最近制作串口通信的项目比较多所以稍微研究了下稍作整理以防忘记,希望也有大佬指正。做串口通信的首先要在菜单–edit–project setting–player 然后看inspector面板,最下面的other setting 把Api Compatibility Level 设置成。Net2..0否则无法使用using System.IO.Ports;如下图设置
串口通信
之后就是上代码了

using RenderHeads.Media.AVProVideo;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using UnityEngine;
using UnityEngine.UI;
using System.Threading;
using System.Xml;
using System.Text;
using System;
using System.Runtime.InteropServices;
public class GameControl : MonoBehaviour {
    /// <summary>
    /// Com端口变量
    /// </summary>
    private string[] allPorts;//所有端口的名字数组
    public string Com = "COM3";
    private byte[] writeData = { 01 };//发送16进制数据
    private bool isAlive = true;//是否可以读取数据
    SerialPort sp;//端口
    bool byte1 = false;
    bool byte2 = false;



    void Start()
    {

        //端口初始化
        allPorts = SerialPort.GetPortNames();//这一步是动态获取目前计算机检测到的所有串口
        sp = new SerialPort(Com, 19200, Parity.None, 8, StopBits.One);//串口名,波特率,奇偶校验位,数据位,停止位。 
        OpenPort();//打开端口
        //Write();
    }

    // Update is called once per frame
    void Update () {

        if (Input.GetKeyDown(KeyCode.A)||byte1==true)
        {
            byte1 = false;                  
        }

        if (Input.GetKeyDown(KeyCode.D) || byte2 == true)
        {
            byte2 = false;
        }

        }

        ///数据处理
        //bytesIndex = sp.Read(dataBytes, 0, dataBytes.Length);//读取数据
        //if (bytesIndex == 0)
        //{
        //    //当没有数据的时后返回
        //    return;
        //}
        //if(bytesIndex !=0)
        //{
        //    DataReceiveFunction(dataBytes);
        //}
    }
    /// <summary>
    /// 打开端口
    /// </summary>
    public void OpenPort()
    {
        sp.ReadTimeout = 100;//端口读取速度

        try
        {
            sp.Open();
            StartCoroutine(DataReceiveFunction());
        }
        catch (Exception ex)
        {
            Debug.Log(ex.Message);
        }
        //Debug.Log(allPorts[1]);
        //Debug.Log(writeData.Length);

    }
    /// <summary>
    /// 发送数据
    /// </summary>
    public void Write()
    {
        if (sp != null)
        {
            sp.Write(writeData, 0, writeData.Length);//写入数据
        }
    }
    /// <summary>
    /// 接受处理数据
    /// </summary>
    public IEnumerator DataReceiveFunction()
    {
        byte[] dataBytes = /*{ 02 };*/new byte[1];//存储数据
        //int bytesIndex = 0;//记录获取的数据长度
        //Debug.Log(dataBytes.Length);
        List<int> byteInt = new List<int>();//接收数据
       // string sbReadline2str = string.Empty;
        while (isAlive)
        {
            if (sp != null && sp.IsOpen)
            {
                try
                {

                    sp.Read(dataBytes, 0, dataBytes.Length);//读取数据
                    if(dataBytes.Length!=0)
                    {
                        byteInt.Add(Convert.ToInt16(dataBytes[0]));
                    }
                    if (byteInt.Count==1)
                    {
                        if (byteInt[0] == 02)
                        {
                            Debug.Log("从头开始并且发送01信号");
                            //Write();
                            StartCoroutine(GeneralMethod.instance.Wait(() => { Write();}, 1f));
                            byte1 = true;//发完信号之后播影片
                            byteInt.Clear();
                            //yield break;
                        }
                        if (byteInt[0] == 03)
                        {
                            //如果接受到信号03
                            _setVideoSeekSliderValue = 0;
                            byte2 = true;                          
                            byteInt.Clear();
                            Debug.Log("结束屏幕变黑");
                            //yield break;
                        }
                    }                  
                }
                catch(Exception ex)
                {
                    Debug.Log(ex.Message);
                }                           
            }
            yield return new WaitForSeconds(Time.deltaTime);
        }

    }
    /// <summary>
    /// 关闭端口
    /// </summary>
    public void ClosePort()
    {
        try
        {
            sp.Close();
        }
        catch (Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }

    private void GarbageCollection()
    {
        if (Time.frameCount % 120 == 0) System.GC.Collect();
    }
    /// <summary>  
    /// 开始事件触发  
    /// </summary>  
    /// <param name="mp"></param>  
    void OnMediaPlayerStarted(MediaPlayer mp)
    {
        print("开始事件触发的后续");

    }
    /// <summary>  
    /// 结束事件触发  
    /// </summary>  
    /// <param name="mp"></param>  
    void OnMediaPlayerFinished(MediaPlayer mp)
    {
        print("结束事件触发的后续");
         byte[] writeData2= { 04 };//发送16进制数据
        sp.Write(writeData2, 0, writeData2.Length);//写入数据
    }
}
相关标签: 串口通信