簡體   English   中英

嘗試將 Arduino 連接到 Unity 時出現超時異常

[英]Timeout Exception when trying to connect Arduino to Unity

當我在 Unity 上按下播放時,我立即收到超時異常 這是我的 Unity 代碼“注釋跳過 stackoverflow 上的錯誤注釋以跳過 stackoverflow 上的錯誤”

    using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System.Threading;

[RequireComponent(typeof(Controller2D))]   

public class Player : MonoBehaviour {

    public float moveSpeed = 6;
    public float gravity = -20;
    public float jumpDistance = 8;
    Vector3 moveDistance;

    SerialPort sp = new SerialPort("COM7", 9600);

    Controller2D controller;    
    void Start() {
        controller = GetComponent<Controller2D>();  
        sp.Open();
        sp.ReadTimeout = 100;
    }

    void Update() {
        if (sp.IsOpen) {
            try {
                print(sp.ReadByte());

            }
            catch (System.Exception) {

                throw;
            }
        }

        if (controller.collisions.above || controller.collisions.below) {   
            moveDistance.y = 0;
        }
        if (Input.GetKeyDown(KeyCode.Space) || sp.ReadByte() == 1 && controller.collisions.below) {   
            moveDistance.y = jumpDistance;
        }
        Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));  


        moveDistance.x = input.x * moveSpeed;   
        moveDistance.y += gravity * Time.deltaTime;     
        controller.Move(moveDistance * Time.deltaTime);     

    }


}

Arduino代碼

const int buttonPin01 = 6;
const int buttonPin02 = 7;
const int buttonPin03 = 8;

void setup() {
  Serial.begin(9600);

  pinMode(buttonPin01, INPUT);
  pinMode(buttonPin02, INPUT);
  pinMode(buttonPin03, INPUT);

  digitalWrite(buttonPin01, HIGH);
  digitalWrite(buttonPin02, HIGH);
  digitalWrite(buttonPin03, HIGH);


}

void loop() {
  if (digitalRead(buttonPin01) == LOW){
    Serial.write(1);
    Serial.flush();
    delay(10);
  }

  if (digitalRead(buttonPin02) == LOW){
    Serial.write(2);
    Serial.flush();
    delay(10);
  }

  if (digitalRead(buttonPin03) == LOW){
    Serial.write(3);
    Serial.flush();
    delay(10);
  }

}

我的錯誤

TimeoutException: The operation has timed out.
System.IO.Ports.WinSerialStream.Read (System.Byte[] buffer, System.Int32 offset, System.Int32 count) (at <3845a180c26b4889bc2d47593a665814>:0)
System.IO.Ports.SerialPort.read_byte () (at <3845a180c26b4889bc2d47593a665814>:0)
System.IO.Ports.SerialPort.ReadByte () (at <3845a180c26b4889bc2d47593a665814>:0)
(wrapper remoting-invoke-with-check) System.IO.Ports.SerialPort.ReadByte()
Player.Update () (at Assets/Script/Player.cs:35)

我嘗試將延遲更改為更高和更低的值,從而更改波特率。 如果有人能發現這個問題,我將不勝感激

更改sp.ReadTimeout = 100; sp.ReadTimeout = 5000;
100 毫秒是快速讀取
我遇到了同樣的問題及其對我的工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM