C#串口问题 - 太简单到失败,但是

Dav*_*ave 3 c# mono serial-port

好的,这应该很简单.我正在尝试从串行设备读取字符.这样,如果我发送一个空格字符,它会回显一串数字和EOL.而已.

我正在使用Unity 3.3(.Net 2.0支持),而'串行端口'是一个Prolific串口转USB适配器.顺便说一句:使用Hyperterminal,一切都很完美,所以我知道它不是驱动程序,也不是硬件.

我可以打开端口了.好像我可以用port.Write("")发送我的空间; 但是,如果我甚至尝试调用ReadChar,ReadByte或ReadLine(如轮询),它会冻结,直到我拔掉USB,我的控制台输出什么都没显示(异常被捕获).

所以我设置了一个DataReceviedHandler,但它永远不会被调用.

我读过一些人们用Arduinos等做过这类事情的帖子(这不是Arduino而是嘿),只使用ReadLine.他们的代码对我不起作用(迄今为止这些作者都没有答案).

那么,有什么提示吗?我需要使用不同的线程吗?如果您知道任何Unity(单声道)编码,那么这些行的任何提示都会受到高度赞赏.

此代码来自http://plikker.com/?p=163http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx#Y537的mashup

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(" ");
 }
}
Run Code Online (Sandbox Code Playgroud)

sko*_*ima 5

事件未在Mono SerialPort类中实现,因此您不会收到任何通知,您必须显式执行(阻塞)读取.其他可能的问题 - 我不确定Unity Behaviors如何工作,你确定所有访问它的方法SerialPort都在同一个线程上调用吗?而且你没有处置你的端口对象,这也会导致问题.