好的,這應該很簡單。我正在嘗試從串口設備讀取字符。這就是說,如果我發送一個空格字符,它會回顯一串數字和EOL。而已。C#串口問題 - 太簡單了,不能失敗,但是
我使用Unity 3.3(.NET 2.0支持),和「串行端口」是一個多產的串行到USB適配器。順便說一下:使用超級終端,這一切都完美,所以我知道這不是驅動程序和硬件。
我可以打開端口確定。看來我可以發送我的空間與port.Write(「」);但是,如果我甚至試圖調用ReadChar,ReadByte或ReadLine(如輪詢),它會凍結,直到我拔掉USB,並且我的控制檯輸出什麼也沒有顯示(異常被捕獲)。
所以不是我設置了一個DataReceviedHandler,但它從來沒有所謂。
我讀過一些帖子裏的人已經做到了這種類型的與Arduinos等東西(這不是一個Arduino但嘿),僅僅使用的ReadLine以上。他們的代碼對我不起作用(迄今爲止還沒有答案)。
所以,任何提示?我需要使用不同的線程嗎?如果您知道任何Unity(單聲道)編碼,那麼非常感謝這些提示。
此代碼混搭從http://plikker.com/?p=163和http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx#Y537
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;
public class SerialTest : MonoBehaviour {
SerialPort stream;
void Start() {
try {
stream = new SerialPort("COM3", 9600);
stream.Parity = Parity.None;
stream.StopBits = StopBits.One;
stream.DataBits = 8;
stream.Handshake = Handshake.None;
stream.DataReceived += new SerialDataReceivedEventHandler(DataReceviedHandler);
stream.Open();
Debug.Log("opened ok"); // it DOES open ok!
} catch (Exception e){
Debug.Log("Error opening port "+e.ToString()); // I never see this message
}
}
void Update() { // called about 60 times/second
try {
// Read serialinput from COM3
// if this next line is here, it will hang, I don't even see the startup message
Debug.Log(stream.ReadLine());
// Note: I've also tried ReadByte and ReadChar and the same problem, it hangs
} catch (Exception e){
Debug.Log("Error reading input "+e.ToString());
}
}
private static void DataReceviedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender; // It never gets here!
string indata = sp.ReadExisting();
Debug.Log("Data Received:");
Debug.Log(indata);
}
void OnGUI() // simple GUI
{
// Create a button that, when pressed, sends the 'ping'
if (GUI.Button (new Rect(10,10,100,20), "Send"))
stream.Write(" ");
}
}
你應該張貼你的代碼,在特別是您打開設備的代碼。 – 2011-04-20 08:30:50
已添加代碼。 – Dave 2011-04-20 19:16:33
你可以嘗試另一種方式,你可以驗證你的程序實際上可以發送出這個端口的東西嗎? – IanNorton 2011-04-20 19:21:48