using UnityEngine;
using System;
using System.IO.Ports;
using UnityEngine.UI;
public class spSend : MonoBehaviour
{
public SerialPort sp;
/* public Text text;*/
static public byte[] strSend = new byte[3];
void Start()
{
sp = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
//串口初始化
try
{
sp.Open();
Debug.Log("成功打开");
//text.text = "成功打开";
}
catch (Exception ex)
{
//text.text = ex.ToString();
Debug.Log(ex);
}
}
//关闭串口
void OnApplicationQuit()
{
sp.Close();
Application.Quit();
}
//发送
public void SendData(byte[] data)
{
if (sp.IsOpen)
{
//text.text = data[0].ToString();
sp.Write(data, 0, data.Length);
}
}
}
使用
public void SendMsg(string s)
{
string msg =s;
byte[] cmd = new byte[1024 * 1024 * 3];
cmd = Convert16(msg);
serialController.SendData(cmd);
}
private 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;
}