0

Good day. I have a problem using unity with arduino,i am using serial port as means of communication of unity to arduino. I am just sending strings from unity to arduino.

After the first player turn an IOException : Access is Denied occurs?. I am unable to play the second players turn because unity stopped after the first player turn. Then it throws , IOException: Access is Denied

UNITY CODE

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

The Above code is the fisrt to execute it will send "green" string to 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;





    }

}

in here the it will send the initial players score and the score after answering a question

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

and lastly here is where to switch or go to next players turn

ARDUINO CODE

#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();
                    }
      }
2
  • Could you please point out the exact line where you get the exception and maybe reduce the code to the absolute necessary information? I don't want to parse all your code in order to eventually find a mistake... Commented Apr 15, 2019 at 5:07
  • The exact line where i get the exception is when i will send the red string to the arduino. The unity suddenly stops before sending the string to arfuino else if (CheckPlayer == "Player2") { sp.Write("red"); } else if (CheckPlayer == "Player3") { sp.Write("blue"); } Commented Apr 15, 2019 at 11:38

1 Answer 1

1

Only one process can use a specific serial port at a time.

COM3 is already opened by SceneManagement , so when others asks to access COM3 will occur access deny.

Use a manager class to handle the SerialPort object, or just call GetComponent<SceneManagement>().GetSP() to get the existing serial port in other scripts.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you please show me how to use this GetComponent?? I am just new to unity. Thank you
@Luigi I am partly with you: This post should be extended with a bit more information/code of implementation in order to convert it to a full valid answer. However please also take the affort to search things on your own ... If you are that new to Unity that you don't know how to use GetComponent and share references between different Components than you shouldn't be doing Port connection but instead get some Unity basics first e.g. Unity GetComponent Tutorial

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.