整体代码:
using System.Collections;
using System.Collections.Generic;
using System.IO.Ports;
using UnityEngine;
using UnityEngine.UI;
public class chuankou : MonoBehaviour
{
//可用串口号缓存
private string[] sps;
//串口号缓存
private string portName;
//波特率
private int baudRate = 9600;
//开关串口判断
private bool close = false;
//开关串口提示
public Text close_text;
//串口号文本
public Text portnames_text;
//获取下拉列表
public Dropdown dp;
//连接状态显示
public GameObject close_gameobject;
//实例化一个串口
public SerialPort serialPort = new SerialPort();
//获取是否成功文本
public Text Great;
//获取当前计算机串口名称
public Text chuankouName;
//显示与编辑内容
public InputField xianshi,bianji;
void Start()
{
//获取串口号
sps = SerialPort.GetPortNames();
//赋值串口号
portName = sps[0];
//显示串口号
portnames_text.text = portName;
//显示当前计算机串口名称
chuankouName.text = "当前计算机串口名:" + SerialPort.GetPortNames().ToString();
}
//搜索设备
public void Get_SerialPort_Names()
{
//重置数组和下拉列表防止重复
for (int i = 0; i < sps.Length; i++)
{
sps[i] = "";
dp.ClearOptions();
}
//赋值给下拉列表
for (int i = 0; i < sps.Length; i++)
{
sps = SerialPort.GetPortNames();
List<string> inside = new List<string> { sps[i] };
dp.AddOptions(inside);
}
//获取串口号
sps = SerialPort.GetPortNames();
//显示串口号
portnames_text.text = portName;
}
//开关串口
public void Open_SerialPort()
{
if (!close)
{
try
{
//定义串口属性变量
serialPort = new SerialPort(portName, baudRate);
//开启串口
serialPort.Open();
Great.text = "已打开串口";
close_text.text = "关闭串口";
close_gameobject.GetComponent<Image>().color = Color.green;
close = true;
}
//报错处理
catch (System.Exception)
{
//关闭串口
serialPort.Close();
close_gameobject.GetComponent<Image>().color = Color.red;
throw;
}
}
else
{
//关闭串口
serialPort.Close();
Great.text = "已关闭串口";
close = false;
close_text.text = "打开串口";
close_gameobject.GetComponent<Image>().color=Color.red;
}
}
public void XianShi()//模拟串口通信
{
xianshi.text += bianji.text+",";
}
public void Exit()//退出
{
Application.Quit();
}
}
?
?
?
?
|