在Unity中尝试双向串行端口通信时,Serial.Write()会导致冻结

时间:2015-04-29 13:40:24

标签: c# unity3d arduino

我正在构建一个Arduino控制器,用于通过串行端口进行通信的Unity游戏。读取从Arduino发送的数据工作得很好,但是当尝试写入串行端口时,Unity立即冻结,需要从任务管理器关闭。我需要一些帮助才能使SerialPort.Write()起作用。下面,我详细介绍了如何从Arduino发送数据并在Unity中成功读取数据,以及我如何尝试将数据写回Arduino,但它无法正常工作。我已经让控制器向Unity发送按钮状态来控制屏幕上的角色,如此

C#,Unity

private SerialPort arduinoStream = new SerialPort("COM3", 38400); 


   void Start(){
   //setup serial connection
        try{
            arduinoStream.ReadBufferSize = 8192;
            arduinoStream.WriteBufferSize = 128;
            arduinoStream.Parity = Parity.None;
            arduinoStream.StopBits = StopBits.One;
            arduinoStream.Open();

            //arduinoStream.BaseStream.ReadTimeout = 20;
        } catch(Exception e){
            Debug.Log("Could not open serial port: " + e.Message);
            useSerialController = false;
        }
     }

    private void SteerAndAccelerateWithArduino(){           
        //attemp to read serial data and handle it
        try{
            string serialData;
            //attempt to read serial data
            serialData = arduinoStream.ReadLine();
            Debug.Log ("serialData received from Arduino: " + serialData);
            HandleSerialInputData(serialData);


        } catch(Exception e){
            //if there's an error, disable serial controller to avoid blocking on serial.read()/write()
            Debug.Log ("serial read error: " + e.Message);
            useSerialController = false;

        }   
        //flush the serial stream
        arduinoStream.BaseStream.Flush();
 }

Arduino用简单的

成功发送数据

C ++,Arduino

Serial.println(buildJSONString(keys,values));
delay(30);

但是一旦我在Unity中尝试向SerialPort写任何东西,它就崩溃了。我试图简单地写一个字符串

C#,Unity

        string serialData = "{blueScore:" + blueScore + ",redScore:" + redScore + "}";
        //write to serial
        try{
            if(arduinoStream.IsOpen)
                arduinoStream.Write (serialData);
        }catch(Exception e){
            Debug.Log ("couldn't write to serial port. " + e.Message);  
        }

在Arduino上我试图一次尝试从Serial中读取一个字符串,但它从来没有这么远,因为Unity崩溃了

C ++,Arduino

void receiveStatesOverSerial(){
  String readString;
  while (Serial.available()) {
    delay(3);  //delay to allow buffer to fill 
    if (Serial.available() >0) {
      char c = Serial.read();  //gets one byte from serial buffer
      readString += c; //makes the string readString
    }
  }

  if (readString.length() >0) {
      Serial.println(readString); //see what was received
  }
  readString = "";

}

有没有人能够在Unity中从同一个SerialPort读取和写入?有人在这看错了吗?任何帮助将不胜感激

0 个答案:

没有答案