Как исправить проблему с Unity для последовательной связи Arduino через последовательный порт - PullRequest
0 голосов
/ 15 апреля 2019

Добрый день. У меня проблема с использованием единства с Arduino, я использую последовательный порт в качестве средства связи единства с Arduino. Я просто посылаю строки из единицы в Arduino.

После первого хода игрока происходит исключение IOException: Доступ запрещен ?. Я не могу играть во втором ходу игроков, потому что единство прекратилось после первого хода игрока. Затем выдает IOException: доступ запрещен

КОД ЕДИНСТВА

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();
                    }
      }

1 Ответ

1 голос
/ 15 апреля 2019

Только один процесс может одновременно использовать определенный последовательный порт.

COM3 уже открыт SceneManagement , поэтому, когда другие запрашивают доступ к COM3, произойдет отказ в доступе.

Используйте класс менеджера для обработки объекта SerialPort или просто вызовите GetComponent<SceneManagement>().GetSP() чтобы получить существующий последовательный порт в других скриптах.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...