當前位置:編程學習大全網 - 編程語言 - unity3d采用串口通信,怎麽接收數據?

unity3d采用串口通信,怎麽接收數據?

通過System.IO.Ports來實現

using?UnityEngine;

using?System.Collections;

using?System.IO.Ports;

using?System;

using?System.IO;

using?System.Collections.Generic;

public?class?PortControl?:?MonoBehaviour

{

public?string?portName?=?"COM3";

public?int?baudRate?=?57600;

public?Parity?parity?=?Parity.None;

public?int?dataBits?=?8;

public?StopBits?stopBits?=?StopBits.One;

SerialPort?sp?=?null;

void?Start()

{

OpenPort();

StartCoroutine(DataReceiveFunction());

}

//打開串口

public?void?OpenPort()

{

sp?=?new?SerialPort(portName,?baudRate,?parity,?dataBits,?stopBits);

sp.ReadTimeout?=?400;

try

{

sp.Open();

}

catch(Exception?ex)

{

Debug.Log(ex.Message);

}

}

//關閉串口

public?void?ClosePort()

{

try

{

sp.Close();

}

catch(Exception?ex)

{

Debug.Log(ex.Message);

}

}

/*

若串口數據速度慢,數量小,可以在Update函數中使用sp.ReadByte等函數,該協程可以不用調用

若串口數據速度較快,數量較多,就調用該協程(該程序就是這壹種,在Start函數中已經被調用)

若串口數據速度非常快,數量非常多,建議使用Thread

*/

IEnumerator?DataReceiveFunction()

{

byte[]?dataBytes?=?new?byte[128];//存儲數據

int?bytesToRead?=?0;//記錄獲取的數據長度

while(true)

{

if(sp?!=?null?&&?sp.IsOpen)

{

try

{

//通過read函數獲取串口數據

bytesToRead?=?sp.Read(dataBytes,?0,?dataBytes.Length);

//串口數據已經被存入dataBytes中

//往下進行自己的數據處理

//比如將妳的數據顯示出來,可以利用guiText.text?=?....之類

}

catch(Exception?ex)

{

Debug.Log(ex.Message);

}

}

yield?return?new?WaitForSeconds(Time.deltaTime);

} 

}

void?OnApplicationQuit()

{

ClosePort?();

}

}

  • 上一篇:壹般來說,程序具有哪些特征?
  • 下一篇:魔獸爭霸3地圖編輯器怎麽用
  • copyright 2024編程學習大全網