【问题标题】:How to fix problem with unity to arduino serial communication via Serial port如何通过串口解决统一到arduino串行通信的问题
【发布时间】:2019-04-15 03:09:20
【问题描述】:

美好的一天。我在使用统一与 arduino 时遇到问题,我使用串行端口作为统一与 arduino 的通信方式。我只是将字符串从 unity 发送到 arduino。

在第一个玩家转弯后,出现 IOException : Access is Denied?。我无法玩第二个玩家回合,因为团结在第一个玩家回合后停止了。 然后抛出,IOException: Access is Denied

统一代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.IO.Ports;

public class SceneManagement : MonoBehaviour
{

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

    // Use this for initialization
    public void CountPlayer()
    {
        SceneManager.LoadScene("CountPlayer");
    }

    public void RandomSubject()
    {
        SceneManager.LoadScene("RandomSubject");
    }

    public void Game()
    {
        if (!sp.IsOpen)
        {
            sp.Open();
            sp.WriteTimeout = 100;
            Debug.Log("Port successfully opened");
        }
        sp.Write("green");
        SceneManager.LoadScene("Game1");
    }
}

上面的代码是第一个执行它会发送“绿色”字符串到arduino

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO.Ports;
public class ButtonCheckAnswerController : MonoBehaviour {

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

    public Text CorrectWrongText;
    public GameManager GameManager;
    public CheckSubjectAndDifficultyController CheckSubjectAndDifficultyController;
    public NextPlayerTurn NextPlayerTurn;
    public string correct = "CORRECT";
    public string wrong = "WRONG";
    public GameObject bgwrong;
    public GameObject bgcorrect;
    public GameObject GameObject;
    public GameObject CorrectAudio;
    public GameObject WrongAudio;
    public GameObject yehey;
    public GameObject awww;

    public List<Text> PlayerText;
    public List<int> PlayerScores;
    public List<GameObject> Players;
    public string PlayerString;
    public string Difficulty;

    public PlayerWinController PlayerWinController;

    void Update()
    {
        if(gameObject.activeInHierarchy == true)
        {
            Invoke("delayScore", .25f);
        }
    }

    void delayScore()
    {
        if (PlayerString == "Player1")
        {
            if(Players[0].activeInHierarchy == false)
            {

                PlayerText[0].text = "Score = " + PlayerScores[0].ToString();
                Players[1].SetActive(false);
                Players[2].SetActive(false);
                Players[0].SetActive(true);
            }

        }
        else if (PlayerString == "Player2")
        {
            if (Players[1].activeInHierarchy == false)
            {
                PlayerText[1].text = "Score = " + PlayerScores[1].ToString();

                Players[0].SetActive(false);
                Players[2].SetActive(false);
                Players[1].SetActive(true);
            }
        }
        else if (PlayerString == "Player3")
        {
            if (Players[2].activeInHierarchy == false)
            {
                PlayerText[2].text = "Score = " + PlayerScores[2].ToString();

                Players[0].SetActive(false);
                Players[1].SetActive(false);
                Players[2].SetActive(true);
            }
        }

        if (!sp.IsOpen)
        {
            sp.Open();
            sp.WriteTimeout = 100;

            if (PlayerString == "Player3")
            {
                sp.Write(PlayerScores[2].ToString());
            }
            else if (PlayerString == "Player2")
            {
                sp.Write(PlayerScores[1].ToString());
            }
            else if (PlayerString == "Player1")
            {
                sp.Write(PlayerScores[0].ToString());
            }

        }

    }

    public void checkAnswer(bool isCorrect)
    {

        if (!sp.IsOpen)
        {
            sp.Open();
            sp.WriteTimeout = 100;
        }
            CorrectAudio.SetActive(false);
            WrongAudio.SetActive(false);
            yehey.SetActive(false);
            awww.SetActive(false);
        bgwrong.SetActive(false);
        bgcorrect.SetActive(false);
        Difficulty = CheckSubjectAndDifficultyController.Difficulty;


        if (isCorrect == true)
        {
            CorrectWrongText.text = correct;
            bgwrong.SetActive(false);
            bgcorrect.SetActive(true);
            CorrectAudio.SetActive(true);

            yehey.SetActive(true);


            if (PlayerString == "Player1")
            {
                if (Difficulty == "Easy")
                {
                    PlayerScores[0]++;
                }
                else if (Difficulty == "Medium")
                {
                    PlayerScores[0] += 3;
                }
                else
                {
                    PlayerScores[0] += 5;
                }
                Debug.Log(PlayerScores[0]);
                sp.Write(PlayerScores[0].ToString());

                //sp.Close();
            }
            else if (PlayerString == "Player2")
            {
                if (Difficulty == "Easy")
                {
                    PlayerScores[1]++;
                }
                else if (Difficulty == "Medium")
                {
                    PlayerScores[1] += 3;
                }
                else
                {
                    PlayerScores[1] += 5;
                }

                sp.Write(PlayerScores[1].ToString());
            }
            else if (PlayerString == "Player3")
            {
                if (Difficulty == "Easy")
                {
                    PlayerScores[2]++;
                }
                else if (Difficulty == "Medium")
                {
                    PlayerScores[2] += 3;
                }
                else
                {
                    PlayerScores[2] += 5;
                }

                sp.Write(PlayerScores[2].ToString());
            }

            PlayerWinController.checkScores();
        }

        else
        {
            CorrectWrongText.text = wrong;
            bgwrong.SetActive(true);
            bgcorrect.SetActive(false);

            WrongAudio.SetActive(true);
            awww.SetActive(true);


            if (PlayerString == "Player1")
            {
                if (Difficulty == "Easy")
                {

                    PlayerScores[0]--;
                    if (PlayerScores[0] < 0)
                    {
                        PlayerScores[0] = 0;
                    }
                }
                else if (Difficulty == "Medium")
                {
                    PlayerScores[0] -= 3;
                    if (PlayerScores[0] < 0)
                    {
                        PlayerScores[0] = 0;
                    }
                }
                else
                {
                    PlayerScores[0] -= 5;
                    if (PlayerScores[0] < 0)
                    {
                        PlayerScores[0] = 0;
                    }
                }

                sp.Write(PlayerScores[0].ToString());
            }
            else if (PlayerString == "Player2")
            {
                if (Difficulty == "Easy")
                {
                    PlayerScores[1]--;
                    if (PlayerScores[1] < 0)
                    {
                        PlayerScores[1] = 0;
                    }
                }
                else if (Difficulty == "Medium")
                {
                    PlayerScores[1] -= 3;
                    if (PlayerScores[1] < 0)
                    {
                        PlayerScores[1] = 0;
                    }
                }
                else
                {
                    PlayerScores[1] -= 5;
                    if (PlayerScores[1] < 0)
                    {
                        PlayerScores[1] = 0;
                    }
                }

                sp.Write(PlayerScores[1].ToString());
            }
            else if (PlayerString == "Player3")
            {
                if (Difficulty == "Easy")
                {
                    PlayerScores[2]--;
                    if (PlayerScores[2] < 0)
                    {
                        PlayerScores[2] = 0;
                    }
                }
                else if (Difficulty == "Medium")
                {
                    PlayerScores[2] -= 3;
                    if (PlayerScores[2] < 0)
                    {
                        PlayerScores[2] = 0;
                    }
                }
                else
                {
                    PlayerScores[2] -= 5;
                    if (PlayerScores[2] < 0)
                    {
                        PlayerScores[2] = 0;
                    }
                }
                sp.Write(PlayerScores[2].ToString());
            }


       }


        GameManager.disableRemoveFromList();
        GameManager.Timer = GameManager.DefaultTimer;





    }

}

在这里,它将发送初始玩家得分和回答问题后的得分

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO.Ports;
public class NextPlayerTurn : MonoBehaviour
{
    SerialPort sp = new SerialPort("COM3", 9600);

    public GameObject Player1Turn;
    public GameObject Player2Turn;
    public GameObject Player3Turn;

    public GameObject PanelPlayerTurn;
    public string CheckPlayer;
    public string PlayerTurn;
    int players;

    public ButtonCheckAnswerController ButtonCheckAnswerController;



    public void checkNextPlayer()
    {


        PanelPlayerTurn.SetActive(true);
        players = PlayerPrefs.GetInt("CountPlayingPlayers");
        PlayerTurn = CheckPlayer;

        if (!sp.IsOpen)
        {
            sp.Open();
        }

        else
        {

            if (players == 2)
            {
                if (CheckPlayer == "Player1")
                {

                    Player1Turn.SetActive(false);
                    Player2Turn.SetActive(true);
                    CheckPlayer = "Player2";
                }
                else
                {

                    Player1Turn.SetActive(true);
                    Player2Turn.SetActive(false);
                    CheckPlayer = "Player1";
                }
            }
            else
            {
                if (CheckPlayer == "Player1")
                {

                    Player1Turn.SetActive(false);
                    Player2Turn.SetActive(true);
                    Player3Turn.SetActive(false);
                    CheckPlayer = "Player2";
                }
                else if (CheckPlayer == "Player2")
                {

                    Player1Turn.SetActive(false);
                    Player2Turn.SetActive(false);
                    Player3Turn.SetActive(true);
                    CheckPlayer = "Player3";
                }
                else
                {


                    Player1Turn.SetActive(true);
                    Player2Turn.SetActive(false);
                    Player3Turn.SetActive(false);
                    CheckPlayer = "Player1";
                }



            }



            if (CheckPlayer == "Player1")
            {
                sp.Write("green");
            }
            else if (CheckPlayer == "Player2")
            {
                sp.Write("red");
            }
            else if (CheckPlayer == "Player3")
            {
                sp.Write("blue");
            }




            ButtonCheckAnswerController.PlayerString = CheckPlayer;
            gameObject.SetActive(false);
        }
    }
}

最后这里是切换或转到下一个玩家的地方

ARDUINO 代码

#include <FastLED.h>
#define LED_PIN     5
#define NUM_LEDS    51
#define BRIGHTNESS  20
#define LED_TYPE    WS2812B
#define COLOR_ORDER RGB
CRGB leds[NUM_LEDS];


String playerColor = "";
String playerQdiff = "";
String playerAnswer = "";
String playerAnsCndtn = "";
String difficulty = "";
String answerCndtn = "";
int i,Red,Green,Blue;
int lastile,initile;
String tileStrt="";
String tileEnd="";

void showProgramRandom(int numIterations, long delayTime) {
  for (int iteration = 0; iteration < numIterations; ++iteration) {
    for (int i = 0; i < NUM_LEDS; ++i) {
      leds[i] = CHSV(random8(),245,255); // hue, saturation, value
    }
    FastLED.show();
    delay(delayTime);
  }
}


void showProgramShiftMultiPixel(long delayTime) {
  for (int i = 0; i < NUM_LEDS; ++i) { 
    for (int j = i; j > 0; --j) {
      leds[j] = leds[j-1];
    }
    CRGB newPixel = CHSV(random8(), 255, 255);
    leds[0] = newPixel;
    FastLED.show();
    delay(delayTime);
  }
}

String getdatainit() {
  while (!Serial.available()) {

     showProgramShiftMultiPixel(50);

  }

  return Serial.readStringUntil("\n");


}



void LedsCleanUp() {
  for (int led = 0; led < NUM_LEDS; ++led) {
    leds[led] = CRGB::Black;
  }
  FastLED.show();

}





void setup() {

    Serial.begin(9600);  

    FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
    FastLED.setBrightness(  BRIGHTNESS );  

}



void loop() {


    GetPlayerColor();

    GetPlayerInitialTile();

    GetPlayersLastTile();





}




        void GetPlayerColor()
            {

              while(!Serial.available())
              {
                showProgramRandom(10, 250);
              }
              LedsCleanUp();
              playerColor = Serial.readString();
              Serial.flush();


        if (playerColor == "red")
               {
                   Red = 255;
                   Green = 0;
                   Blue = 0;
               }
        else if(playerColor == "green")
                {
                   Red = 0;
                   Green = 255;
                   Blue = 0;  
                }
        else if(playerColor == "blue")
                {
                   Red = 0;
                   Green = 0;
                   Blue = 255;  
                }   
            }



      void ShowPlayerColor()
          {
           for (i = 0; i <= NUM_LEDS; i++)
             { 
               leds[i] = CRGB (Green, Red, Blue);
               FastLED.show();
             }

            delay(2000);  
          }


      void GetPlayerInitialTile()
      {

     while(!Serial.available())
              {
                showProgramRandom(10,250);
              }
              Serial.flush();
              tileStrt = Serial.readString();



    LedsCleanUp();

    initile = tileStrt.toInt();
    leds[initile] = CRGB (Green, Red, Blue);
    FastLED.show();
    delay(2000);

      }


        void GetPlayersLastTile()
      {
        while(!Serial.available())
              {
                ;
              }
              Serial.flush();
              tileEnd = Serial.readString();
              LedsCleanUp();
              lastile = tileEnd.toInt();



      if (lastile < initile)
            {
                for (i = initile; i >= lastile; i--)
              {
               leds[i] = CRGB (Green, Red, Blue); 
               delay(650);
               FastLED.show();
              }
              delay(650);
              LedsCleanUp();

            }
       else
            {
              for (i = initile; i <= lastile; i++)
              {
               leds[i] = CRGB (Green, Red, Blue); 
               delay(650);
               FastLED.show();
              }
              delay(650);
              LedsCleanUp();

            }

                  for (i = 0; i<=3; i++ )
                   { 
                    leds[lastile] = CRGB (Green, Red, Blue); 
                    delay(650);
                    FastLED.show();
                    leds[lastile] = CRGB (0,0,0); 
                    delay(650);
                     FastLED.show();
                    }
      }

【问题讨论】:

  • 您能否指出您得到异常的确切行,并可能将代码减少到绝对必要的信息?我不想解析你所有的代码以便最终找到错误......
  • 我得到异常的确切行是我何时将红色字符串发送到 arduino。统一在将字符串发送到 arfuino 之前突然停止 else if (CheckPlayer == "Player2") { sp.Write("red"); } else if (CheckPlayer == "Player3") { sp.Write("blue"); }

标签: c# unity3d arduino


【解决方案1】:

一次只有一个进程可以使用特定的串行端口。

COM3 已经被 SceneManagement 开启,所以当其他人请求访问 COM3 时会出现拒绝访问。

使用管理器类来处理 SerialPort 对象,或者只是调用 GetComponent&lt;SceneManagement&gt;().GetSP() 在其他脚本中获取现有的串口。

【讨论】:

  • 你能告诉我如何使用这个GetComponent吗?我只是新来的团结。谢谢
  • @Luigi 我部分支持你:这篇文章应该使用更多信息/实现代码进行扩展,以便将其转换为完整的有效答案。但是,也请自行搜索内容...如果您是 Unity 新手,不知道如何使用 GetComponent 并在不同组件之间共享引用,那么您不应该进行端口连接,但是而是首先获得一些 Unity 基础知识,例如Unity GetComponent Tutorial
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-01
  • 2023-04-05
  • 1970-01-01
  • 2019-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多