串口通信

串口通信

 

在对串口进行编程时候,我们要向串口发送指令,然后我们解析串口返回的指令。从.NET Framework 2.0开始,C#提供了SerialPort类用于实现串口控制。命名空间:System.IO.Ports。

1、 常用的字段:
PortName:获取或设置通信端口
BaudRate:获取或设置串行波特率Parity:获取或设置奇偶效验检查协议
DataBits:获取或设置每个字节的标准数据位长度
StopBits:获取或设置每个字节的标准停止位数

2、 常用方法:
Open:打开一个新的串行端口连接
Close:关闭端口连接,将IsOpen属性设置false,并释放内部Stream对象
Read:从SerialPort输入缓冲区中读取
Write:将数据写入串行端口输出缓冲区
GetPortNames:获取当前计算机的串行端口名称数组

3、常用事件:
DataReceived:表示将处理SerialPort对象的数据接收事件的方法
DisPosed:通过调用释放组件时发生Dispose方法(继承自Component)

4、SerialPort 控件使用流程
流程是设置通信端口号及波特率、数据位、停止位和校验位,再打开端口连接、发送数据、接收数据,最后关闭端口连接步骤。

注意:使用Unity是进行串口通信的时候,需要在Project Setting=>Player=>Other Settings=>Configuration中将API  Compatibility Level 改成Mono.NET 2.0/4.0/其他。

 
代码示例
using System.IO.Ports;
using System.Linq;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;

public class RideSpeedSetter : MonoBehaviour
{
    private SerialPort serialPort;

    public string portName = "COM3";//串口名
    public int baudRate = 115200;//波特率
    public Parity parity = Parity.None;//效验位
    public int dataBits = 8;//数据位
    public StopBits stopBits = StopBits.One;//停止位

    public Slider speedSlider;
    public Button startBtn;
    public Button stopBtn;
    public Button exitBtn;
    public Text speedText;
    public Text angleText;

    public Thread receCOMData;

    void Start()
    {
        startBtn.onClick.AddListener(() => { StratRide(); });
        stopBtn.onClick.AddListener(() => { StopRide(); });
        exitBtn.onClick.AddListener(() => { Exit(); });
        speedSlider.onValueChanged.AddListener((value) => { SpeedControl(value); });

        serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
        if (!serialPort.IsOpen)
        {
            serialPort.Open();
            //serialPort.WriteTimeout = 300;//com写入数据时间限制
            //serialPort.ReadTimeout = 300;//com读取数据时间限制
        }

        receCOMData = new Thread(ReceCOMData);
        receCOMData.Start();
    }

    float timeCount = 0;
    void FixedUpdate()
    {
        timeCount += Time.fixedDeltaTime;
        if (timeCount > 0.09f)
        {
            if (!receCOMData.IsAlive)
            {
                receCOMData = new Thread(ReceCOMData);
                receCOMData.Start();
            }
            timeCount = 0;
            ShowSpeed();
        }
    }

    string data;
    private void ReceCOMData()
    {
        while (serialPort.IsOpen)
        {
            data = serialPort.ReadLine();
        }
    }

    void StratRide()
    {
        SendData("A01\r\n");
        Invoke("StartB", 1.2f);
    }

    void StartB()
    {
        SendData("B01\r\n");
    }

    void StopRide()
    {
        SendData("A00\r\n");
        Invoke("StopB", 1.2f);
    }

    void StopB()
    {
        SendData("B00\r\n");
    }

    string speedValue;
    void SpeedControl(float value)
    {
        speedValue = "PWM" + ((int)(value * 80) + 10).ToString() + "\n";
        SendData(speedValue);
    }

    void SendData(string data)
    {
        if (serialPort != null && serialPort.IsOpen)
        {
            serialPort.Write(data);
        }
    }

    float speedRate = 0.15f;
    void ShowSpeed()
    {
        angleText.text = "Received Data: " + data;
        speedText.text = "Speed: " + (speedRate * GetSpeed()).ToString("#0.00");
    }

    float curNum = 0;
    float lastNum = 0;
    float speed;
    float GetSpeed()
    {
        if (!data.Contains(',')) return 666;
        int index = data.IndexOf(',');
        string before = data.Remove(index);
        string after = data.Substring(index + 1);
        curNum = float.Parse(after);
        speed = curNum - lastNum;
        lastNum = curNum;
        return speed;
    }

    void CloseSerialPort()
    {
        if (serialPort != null && serialPort.IsOpen)
        {
            serialPort.Close();
        }
    }

    void Exit()
    {
#if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
#else
        Application.Quit();
#endif
    }

    void OnApplicationQuit()
    {
        receCOMData.Abort();
        StopRide();
        Invoke("CloseSerialPort", 1.5f);
    }
}

  

 
posted @ 2024-03-27 14:43  gatran  阅读(20)  评论(0编辑  收藏  举报