Unity SerialPort 实现 串口通讯

Unity与串口通信,利用SerialPort,传入硬件的串口号于波特率,SerialPort的内置方法打开串口(关闭串口),写入数据(发送数据)等。代码在SerialPort中也都给封装好了。

using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;

public class MyComSocket : MonoBehaviour
{
	//串口号(CM3、CM8)
	private string portName;
	//硬件波特率信息
    public int baudRate;
    public Parity parity = Parity.None;
    public int dataBits = 8;
    public StopBits stopBits = StopBits.One;
    //记录当前连接的硬件信息
    public SerialPort sp = null;
    
	//打开Com口
    public void OpenPort()
    {
        portName = CM3;
        baudRate = 9600;
        /*
         * 也可以使用这个连接串口,其他也不可以不用配置
         * sp = new SerialPort("COM4", 9600);         
         */
        sp = new SerialPort(portName, baudRate, parity, dataBits, stopBits);        
        //端口读取速度
        sp.ReadTimeout = 50;
        try
        {
            sp.Open();
        }
        catch (Exception ex)
        {
            Debug.LogError(ex.Message);
        }
    }
    //关闭Com口
    public void ClosePort()
    {
        try
        {
            sp.Close();
        }
        catch (Exception ex)
        {
            Debug.LogError(ex.Message);
        }
    }
    //给硬件发送数据
    public void WriteData(string dataStr)
    {
        if (sp.IsOpen)
        {
            sp.Write(dataStr);
        }
    }
    //退出时关闭com口
    public void OnApplicationQuit()
    {
        ClosePort();
    }
}
  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值