1.修改unity设置
将Edit->Project Seetings...->Api Compatibility Level*修改为.NET Framework
2.新建一个C#脚本编写脚本
public class SerialPortScript : MonoBehaviour
{
private static string portName = "COM7"; // 端口号
private static int baudRate = 115200; // 波特率
private static int dataBit = 8; // 数据位
private static Parity parity = Parity.None; // 校验位
private static StopBits stopBit = StopBits.One; // 停止位
SerialPort sp = null;
// 打开串口
public void OpenPort()
{
// 创建串口
sp = new SerialPort(portName, baudRate, parity, dataBit, stopBit);
sp.ReadTimeout = 100;
try
{
sp.Open();
Debug.Log("Open the serial port successfully!");
}
catch (Exception e)
{
Debug.Log("Open the serial port error: " + e.Message);
}
}
// 接收数据
public static void DataRecive()
{
byte[] buf = new byte[1024];
int bytes = 0;
while(true)
{
if(sp != null && sp.IsOpen)
{
try
{
bytes = sp.Read(buf, 0, buf.Length); // 接收字节
if(bytes == 0)
{
continue;
}
else
{
string data = Encoding.Default.GetString(buf);
Debug.Log("Recive: " + data);
}
}
catch(Exception e)
{
Console.WriteLine("Received data error: " + e);
}
}
}
Thread.Sleep(10);
}
void Start()
{
OpenPort();
}
void OnDestroy()
{
sp.Close(); // 关闭串口
}
}