Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Arduino Buttons To Toggle Animation Help

Discussion in 'Scripting' started by KnightRiderGuy, Dec 25, 2015.

  1. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Ok this might be a little tricky to explain right. But first off let me try and be clear by saying that I'm trying to make a button on my breadboard connected to the Arduino act like the Left Turn Signal Switch in your car.
    My code is a little buggy, it works for the most part, "just buggy" for lack of a better word. On the Arduino code I have my setup basically like this.

    Code (CSharp):
    1. const int buttonPin01 = A1; //Defines Our Button Pins
    2. const int buttonPin02 = A2;
    3.  
    4. void setup()
    5. {
    6.   //Serial.begin (9600);
    7.   Serial.begin (115200);
    8.   Serial.setTimeout(13); //Added today Sun Nov 22 ( not sure if this is needed? )
    9.  
    10.   pinMode(buttonPin01, INPUT); //Defines Pin Mode
    11.   pinMode(buttonPin02, INPUT);
    12.  
    13.   digitalWrite(buttonPin01, HIGH);
    14.   digitalWrite(buttonPin02, HIGH);
    15.  
    16. }
    17.  
    18. void loop()
    19. {
    20. if (Serial.available())              //if serial data is available
    21.   {
    22.  
    23. if(digitalRead(buttonPin01) == LOW)
    24.   {
    25.     //Serial.println("LEFT");
    26.     Serial.write(8);
    27.     Serial.flush();
    28.     delay(20);
    29.   }
    30.   if(digitalRead(buttonPin02) == LOW)
    31.   {
    32.     //Serial.println("RIGHT");
    33.     Serial.write(9);
    34.     Serial.flush();
    35.     delay(20);
    36.   }
    37. }
    On my Unity side and I think this is where its being a little buggy with the way I have it set up in Update??
    The void DirectionArrow(int Direction) part calls to animation on another script and game object.

    Code (CSharp):
    1. // Update is called once per frame
    2.     void Update () {
    3.         try
    4.         {
    5.             DirectionArrow(sp.ReadByte());
    6.             print(sp.ReadByte());
    7.         }
    8.         catch (System.Exception) {
    9.  
    10.         }
    11.             //print("BytesToRead" +sp.BytesToRead);
    12.             message2 = sp.ReadLine();
    13.            
    14.         string message = sp.ReadLine(); //get the message...
    15.         if(message == "") return; //if its empty stop right here
    16.         // parse the input to a float and normalize it (range 0..1) (we could do this already in the Arduino)
    17.  
    18.         float input =  1 -  float.Parse (message) / 100f;
    19.         // set the slider to the value
    20.         float oldValue = slider.value; // -------- this is new
    21.         slider.value = input;
    22.  
    23.         // after the slider is updated, we can check for the other things for example play sounds:
    24.  
    25.         if (source.isPlaying) return; // if we are playing a sound stop here
    26.  
    27.         // else check if we need to play a sound and do it
    28.         if (slider.value > 0.9f && oldValue <= 0.9f) // ---------this has changed
    29.             source.PlayOneShot (BrightnessAudioClips [Random.Range (0, BrightnessAudioClips.Length)]);
    30.  
    31.         else if (slider.value < 0.15f && oldValue >= 0.15f) //----------this has changed
    32.             source.PlayOneShot (DarknessAudioClips [Random.Range (0, DarknessAudioClips.Length)]);
    33.        
    34.  
    35.     }
    36.        
    37. void DirectionArrow(int Direction)
    38.     {
    39.         //ON Button  State
    40.         if (Direction == 8) {
    41.             //Activate Left Direction Arrow Indicator
    42.             SystemGuidanceManagerScript sgms = FindObjectOfType<SystemGuidanceManagerScript>();
    43.             sgms.WestArrow();
    44.  
    45.             SystemGuidanceManagerScript sgmsEOff = FindObjectOfType<SystemGuidanceManagerScript>();
    46.             sgmsEOff.EastArrowOff();
    47.  
    48.             SystemGuidanceManagerScript sgmsTIon = FindObjectOfType<SystemGuidanceManagerScript>();
    49.             sgmsTIon.TopIndicatorOn();
    50.         }
    51.         if (Direction == 9) {
    52.             //Activate Right Direction Arrow Indicator
    53.             SystemGuidanceManagerScript sgms = FindObjectOfType<SystemGuidanceManagerScript>();
    54.             sgms.EastArrow();
    55.  
    56.             SystemGuidanceManagerScript sgmsWOff = FindObjectOfType<SystemGuidanceManagerScript>();
    57.             sgmsWOff.WestArrowOff();
    58.  
    59.             SystemGuidanceManagerScript sgmsTIon = FindObjectOfType<SystemGuidanceManagerScript>();
    60.             sgmsTIon.TopIndicatorOn();
    61.         }
    62. }
    What happens is that if you hold the button down it's like it tries to play the animation and sounds repeatedly.
    I was wondering if there is a way to have it so that if the button is held down the animation and sound are triggered and if the button is released the animation and sound stops. It does this but "Buggy"
     
  2. Polymorphik

    Polymorphik

    Joined:
    Jul 25, 2014
    Posts:
    599
    Give me 1 sec.
     
  3. Polymorphik

    Polymorphik

    Joined:
    Jul 25, 2014
    Posts:
    599
    So this is all psuedo code, not tested as I do not have your rig but this should give you a template as to what it is you need to do.

    Hope this helps.

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5.  
    6. /// <summary>
    7. /// W/E sp stands for.
    8. /// </summary>
    9. public class SP : System.Object {
    10.     public static int ReadByte() { return 0; }
    11. }
    12.  
    13.  
    14. /// <summary>
    15. /// Some wrapper
    16. /// </summary>
    17. public class Wrapper : MonoBehaviour {
    18.     static Wrapper _instance = null;
    19.     static object _lock = new object();
    20.  
    21.     static Wrapper _SceneInstance {
    22.         get {
    23.             lock(Wrapper._lock) {
    24.                 if(Wrapper._instance == null) {
    25.                     Wrapper._instance = Object.FindObjectOfType<Wrapper>();
    26.  
    27.                     if(Wrapper._instance == null) {
    28.                         GameObject go = new GameObject(typeof(Wrapper).ToString());
    29.  
    30.                         Wrapper._instance = go.AddComponent<Wrapper>();
    31.                     }
    32.                 }
    33.             }
    34.  
    35.             return Wrapper._instance;
    36.         }
    37.     }
    38.  
    39.     delegate void OnUpdate();
    40.     event OnUpdate m_onUpdate;
    41.     List<AInputListener> m_inputListeners = new List<AInputListener>();
    42.  
    43.     void Start() {
    44.         AInput[] aInput = (AInput[])System.Enum.GetValues(typeof(AInput));
    45.  
    46.         for(int i = 0; i < aInput.Length; i++) {
    47.             this.m_inputListeners.Add(new AInputListener(aInput[i]));
    48.             this.m_onUpdate += this.m_inputListeners[i].Listen;
    49.         }
    50.     }
    51.  
    52.     void Update() {
    53.         if(this.m_onUpdate != null) {
    54.             this.m_onUpdate.Invoke();
    55.         }
    56.     }
    57.  
    58.     public static AInputState GetState(AInput input) {
    59.         return Wrapper._SceneInstance.m_inputListeners.Find(i => i.Input == input).State;
    60.     }
    61.  
    62.     public static bool IsDown(AInput input) {
    63.         return Wrapper._SceneInstance.m_inputListeners.Find(i => i.Input == input).IsDown;
    64.     }
    65.  
    66.     public static bool IsPressed(AInput input) {
    67.         return Wrapper._SceneInstance.m_inputListeners.Find(i => i.Input == input).IsPressed;
    68.     }
    69.  
    70.     public static bool IsUp(AInput input) {
    71.         return Wrapper._SceneInstance.m_inputListeners.Find(i => i.Input == input).IsUp;
    72.     }
    73. }
    74.  
    75. /// <summary>
    76. /// A listener object
    77. /// </summary>
    78. public class AInputListener : System.Object {
    79.     AInput m_input;
    80.     AInputState m_state;
    81.     AInputState m_lastInput;
    82.     bool m_isDown;
    83.     bool m_isUp;
    84.     bool m_isPressed;
    85.  
    86.     public AInput Input {
    87.         get {
    88.             return this.m_input;
    89.         }
    90.     }
    91.  
    92.     public AInputState State {
    93.         get {
    94.             return this.m_state;
    95.         }
    96.     }
    97.  
    98.     public bool IsDown {
    99.         get {
    100.             return this.m_isDown;
    101.         }
    102.     }
    103.  
    104.     public bool IsPressed {
    105.         get {
    106.             return this.m_isPressed;
    107.         }
    108.     }
    109.  
    110.     public bool IsUp {
    111.         get {
    112.             return this.m_isUp;
    113.         }
    114.     }
    115.  
    116.     public AInputListener(AInput input) {
    117.         this.m_input = input;
    118.     }
    119.  
    120.     public void Listen() {
    121.         AInput readByte = (AInput)SP.ReadByte();
    122.  
    123.         if(readByte == this.m_input) {
    124.             if(this.m_lastInput == AInputState.None) {
    125.                 this.m_state = AInputState.Down;
    126.             } else {
    127.                 this.m_state = AInputState.Pressed;
    128.             }
    129.         } else {
    130.             if(this.m_lastInput == AInputState.Pressed) {
    131.                 this.m_state = AInputState.Up;
    132.             } else {
    133.                 this.m_state = AInputState.None;
    134.             }
    135.         }
    136.  
    137.         switch(this.m_state) {
    138.             case AInputState.Down: {
    139.                 this.m_isDown = true;
    140.                 this.m_isPressed = true;
    141.                 this.m_isUp = false;
    142.             } break;
    143.             case AInputState.Pressed: {
    144.                 this.m_isDown = false;
    145.                 this.m_isPressed = true;
    146.                 this.m_isUp = false;
    147.             } break;
    148.             case AInputState.Up: {
    149.                 this.m_isDown = false;
    150.                 this.m_isPressed = false;
    151.                 this.m_isUp = true;
    152.             } break;
    153.             case AInputState.None: {
    154.                 this.m_isDown = false;
    155.                 this.m_isPressed = false;
    156.                 this.m_isUp = false;
    157.             } break;
    158.         }
    159.  
    160.         this.m_lastInput = this.m_state;
    161.     }
    162. }
    163.  
    164. /// <summary>
    165. /// Input States the value should be equal to the byte the
    166. /// arduino outputs.
    167. /// </summary>
    168. public enum AInput {
    169.     Up = 0,
    170.     Down = 1,
    171.     Left = 2,
    172.     Right = 3
    173. }
    174.  
    175. /// <summary>
    176. /// Input States.
    177. /// </summary>
    178. public enum AInputState {
    179.     None = 0,
    180.     Down = 1,
    181.     Pressed = 2,
    182.     Up = 3
    183. }
    184.  
    185. /// <summary>
    186. /// Use case.
    187. /// </summary>
    188. public class Demo : MonoBehaviour {
    189.     void Update() {
    190.         if(AInputState.Down == Wrapper.GetState(AInput.Left)) {
    191.             // Do something...
    192.             /*
    193.              * So, in order for this to work, the above psudo code needs to be done. Basically the error
    194.              * you are getting is because your logic is faulty. Basically what you are telling Unity
    195.              * is whenever a certain button is pressed
    196.              * continously play the audio clip etc.
    197.              * Were in fact when the button is pressed down then you want it to play,
    198.              * just once. to stop the clip look below.
    199.              */
    200.         }
    201.  
    202.         if(AInputState.Up == Wrapper.GetState(AInput.Left)) {
    203.             // Do something...
    204.             /*
    205.              * So, here you can stop the audio clip from playing we have entered the state
    206.              * in which the arduino button has been lifted.
    207.              * Its not so easy to do things when you don't create a wrapper for external tools. This should
    208.              * give you the basics as to what you need to do first, before querying the arduino for the states of its buttons
    209.              * so you can use those inputs in Unity.
    210.              */
    211.         }
    212.     }
    213. }
    214.  
     
    Last edited: Dec 25, 2015
  4. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Holy Martian Bat Man!!
    Thanks Polymorthik,
    That's a whole lot of code for a couple of buttons ?? It's going to take a me a little time to decipher the "Martian" ;)
    give me a mo, I'll upload a video that might clarify my somewhat whacky Unity & Arduino scenario ;)
     
  5. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    he he he..... OK here is my video I promised that kind of demos what I'm trying to do. ;)
     
  6. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Holy Pandemonium Batman!!

    I kinda get some of what you have going on here Polymorphik, I have been trying to implement some of what you have here but now it's total chaos lol :)
    My buttons are working but there is a sheep-dip load of other chaos going on with my sounds and animations and My LDR sensor seems to be messed up now.

    Here is my code for my sending script, maybe you might see what & where I'm messing up.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4. using System.IO.Ports;
    5. using System.Threading;
    6.  
    7.  
    8. public class Sending : MonoBehaviour {
    9.  
    10.  
    11.     //int sysHour = System.DateTime.Now.Hour;
    12.    
    13.     //Random Clips
    14.     public AudioClip[] BrightnessAudioClips;
    15.     public AudioClip[] DarknessAudioClips;
    16.     public AudioClip[] AnnoyedAudioClips;
    17.  
    18.     //DTMF Tones
    19.     public AudioClip DTMFtone01;
    20.     public AudioClip DTMFtone02;
    21.     public AudioClip DTMFtone06;
    22.     public AudioClip DTMFtone08;
    23.     public AudioSource source;
    24.  
    25.     //UI Text Reference
    26.     //public Text MessageCentreText;
    27.  
    28.     //_isPlayingSound is true when a sound is currently playing - just as the name suggests.
    29.     private bool _isPlayingSound;
    30.  
    31.     const float sliderChangeVelocity = 0.5f;
    32.     private float desiredSliderValue;
    33.  
    34.     public GameObject LightSlider;
    35.     public Slider slider;
    36.     Slider lightSlider;
    37.     public static Sending sending;
    38.  
    39.     //public static SerialPort sp = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
    40.     public static SerialPort sp = new SerialPort("/dev/cu.wchusbserial1420", 115200); //115200
    41.  
    42.     public string message2;
    43.  
    44.     //Button States
    45.     bool button01State = false;
    46.  
    47.  
    48.     void Awake () {
    49.         if (sending == null) {
    50.             DontDestroyOnLoad (gameObject);
    51.             sending = this;
    52.         } else if (sending != this) {
    53.             Destroy (gameObject);
    54.         }
    55. }
    56.  
    57.  
    58.     float timePassed = 0.0f;
    59.     // Use this for initialization
    60.     void Start () {
    61.         //OpenConnection();
    62.         StartCoroutine(OpenConnection());
    63.         lightSlider = GetComponent<Slider> ();
    64.         if(slider == null) slider = GetComponent<Slider>(); // search slider in this object if its not set in unity inspector
    65.         if(source == null) source = GetComponent<AudioSource>(); // search audiosource in this object if its not set in unity inspector
    66.  
    67.         }
    68.    
    69.     // Update is called once per frame
    70.     void Update () {
    71.         string dataFromArduinoString = sp.ReadLine ();
    72.         int dFAI = int.Parse (dataFromArduinoString);
    73.         print (dFAI);
    74.         DirectionArrow (dFAI);
    75.  
    76.         /*try
    77.         {
    78.             DirectionArrow(sp.ReadByte());
    79.             print(sp.ReadByte());
    80.         }
    81.         catch (System.Exception) {
    82.  
    83.         }*/
    84.             //print("BytesToRead" +sp.BytesToRead);
    85.             message2 = sp.ReadLine();
    86.            
    87.         string message = sp.ReadLine(); //get the message...
    88.         if(message == "") return; //if its empty stop right here
    89.         // parse the input to a float and normalize it (range 0..1) (we could do this already in the Arduino)
    90.  
    91.         float input =  1 -  float.Parse (message) / 100f;
    92.         // set the slider to the value
    93.         float oldValue = slider.value; // -------- this is new
    94.         slider.value = input;
    95.  
    96.         // after the slider is updated, we can check for the other things for example play sounds:
    97.  
    98.         if (source.isPlaying) return; // if we are playing a sound stop here
    99.  
    100.         // else check if we need to play a sound and do it
    101.         if (slider.value > 0.9f && oldValue <= 0.9f) // ---------this has changed
    102.             source.PlayOneShot (BrightnessAudioClips [Random.Range (0, BrightnessAudioClips.Length)]);
    103.  
    104.         else if (slider.value < 0.15f && oldValue >= 0.15f) //----------this has changed
    105.             source.PlayOneShot (DarknessAudioClips [Random.Range (0, DarknessAudioClips.Length)]);
    106.        
    107.  
    108.     }
    109.        
    110.  
    111.  
    112.     //public void OpenConnection() {
    113.     IEnumerator OpenConnection(){
    114.         yield return new WaitForSeconds(1.9f); // wait time
    115.        if (sp != null)
    116.        {
    117.          if (sp.IsOpen)
    118.          {
    119.           sp.Close();
    120.           print("Closing port, because it was already open!");
    121.          }
    122.          else
    123.          {
    124.           sp.Open();  // opens the connection
    125.           sp.ReadTimeout = 16;  // sets the timeout value before reporting error
    126.           print("Port Opened!");
    127.         //        message = "Port Opened!";
    128.          }
    129.        }
    130.        else
    131.        {
    132.          if (sp.IsOpen)
    133.          {
    134.           print("Port is already open");
    135.          }
    136.          else
    137.          {
    138.           print("Port == null");
    139.          }
    140.        }
    141.     }
    142.  
    143.     void OnApplicationQuit()
    144.     {
    145.        sp.Close();
    146.     }
    147.  
    148.     //Movie Player Toggle
    149.     public static void sendYellow(){
    150.         sp.Write("y");
    151.     }
    152.  
    153.     //Analyzer Toggle
    154.     public static void sendYellow2(){
    155.         sp.Write("A");
    156.     }
    157.  
    158.     //Pod 7DLA Toggle
    159.     public static void sendYellow3(){
    160.         sp.Write("D");
    161.     }
    162.  
    163.     //Pod PENG Toggle
    164.     public static void sendYellow4(){
    165.         sp.Write("P");
    166.     }
    167.  
    168.     //Pod 6RM Toggle
    169.     public static void sendYellow5(){
    170.         sp.Write("6");
    171.     }
    172.  
    173.     //Pod Laser Toggle
    174.     public static void sendYellow6(){
    175.         sp.Write("Z");
    176.     }
    177.  
    178.  
    179.     //Auto Phone Toggle
    180.     public static void sendGreen(){
    181.         sp.Write("g");
    182.         //sp.Write("\n");
    183.     }
    184.    
    185.     //Oil Slick Toggle
    186.     public static void sendRed(){
    187.         sp.Write("r");
    188.     }
    189.  
    190.     //Surveillance Mode Toggle
    191.     public static void sendBlue(){
    192.         sp.Write("b");
    193.     }
    194.    
    195.     //Scanner Toggle
    196.     public static void sendRed2(){
    197.         sp.Write("1");
    198.     }
    199.  
    200.     //Fog Lights Toggle
    201.     public static void sendGreen2(){
    202.         sp.Write("f");
    203.     }
    204.  
    205.     //Head Lights Toggle
    206.     public static void sendGreen3(){
    207.         sp.Write("h");
    208.     }
    209.  
    210.     //Hight Beams Toggle
    211.     public static void sendWhite(){
    212.         sp.Write("H");
    213.     }
    214.  
    215.     //Rear Hatch Popper
    216.     public static void sendPulse1(){
    217.         sp.Write("p");
    218.     }
    219.    
    220.     //Grappling Hook Launch
    221.     public static void sendPulse2(){
    222.         sp.Write("q");
    223.     }
    224.  
    225.     //Auto Doors Right Pulse
    226.     public static void sendPulse3(){
    227.         sp.Write("R");
    228.     }
    229.  
    230.     //Auto Doors Left Pulse
    231.     public static void sendPulse4(){
    232.         sp.Write("L");
    233.     }
    234.  
    235.     //Startup and Shutdown Pulse
    236.     public static void sendPulse5(){
    237.         sp.Write("S");
    238.     }
    239.        
    240.  
    241.     //System Guidance Close Button
    242.     public void  GoDTMFtone02(){
    243.         StartCoroutine(LoadT4());
    244.         GetComponent<AudioSource>().PlayOneShot(DTMFtone02);
    245.     }
    246.  
    247.     IEnumerator LoadT4(){
    248.         yield return new WaitForSeconds(0.0f); // wait time
    249.         CameraSwitcher cs1 = FindObjectOfType<CameraSwitcher>();
    250.         cs1.EnableCamera1();
    251.     }
    252.        
    253.     void DirectionArrow(int buttonStatus)
    254.     //void DirectionArrow(int Direction)
    255.     {
    256.     switch (buttonStatus)
    257.     {
    258.         //ON Button  State
    259.         case 0:
    260.             //deactivate Left Direction Arrow
    261.             SystemGuidanceManagerScript sgmsO = FindObjectOfType<SystemGuidanceManagerScript>();
    262.             sgmsO.WestArrowOff ();
    263.  
    264.             SystemGuidanceManagerScript sgmsEOff = FindObjectOfType<SystemGuidanceManagerScript>();
    265.             sgmsEOff.EastArrowOff();
    266.             break;
    267.    
    268.         case 4:
    269.             //Activate Left Direction Arrow Indicator
    270.             SystemGuidanceManagerScript sgms = FindObjectOfType<SystemGuidanceManagerScript>();
    271.             sgms.WestArrow();
    272.             break;
    273.  
    274.         case 5:
    275.             //Activate Right Direction Arrow Indicator
    276.             SystemGuidanceManagerScript sgms2 = FindObjectOfType<SystemGuidanceManagerScript>();
    277.             sgms2.EastArrow();
    278.             break;
    279.     }
    280.            
    281.     }
    282.  
    283. }
    284.  
    This is my complete Arduino Code:

    Code (CSharp):
    1.  
    2. int lightSensorPin = A0; //Define the Light Sensor Pin
    3. int lightSensorValue = 0;
    4.  
    5. //int lightLevel = analogRead(0);
    6. //int threshold = 250;
    7. //int range = 50;
    8.  
    9. //Defines Our Button Pins
    10. const int buttonRight = A1;
    11. const int buttonLeft = A2;
    12.  
    13. // Variable to hold the state of the buttons
    14. int bRS, bLS; //ButtonRight and ButtonLeft states status holders
    15.  
    16. //Sets Pin number LED is conneted too
    17. const byte rLed = 12;
    18. const byte rLed2 = 1;
    19. const byte yLed = 11;
    20. const byte gLed = 10;
    21. const byte gLed2 = 5;
    22. const byte gLed3 = 4;
    23. const byte wLed = 3;
    24. const byte bLed = 2;
    25. const byte bLed2 = 13;
    26.  
    27. char myChar;         //changed the name of this variable because they are not all colurs now
    28. const byte pulsePins[] = {6, 7, 8, 9};  //pins for a pulse output
    29. char pulseTriggers[] = {'p', 'q','R','L'};
    30. const int NUMBER_OF_PULSE_PINS = sizeof(pulsePins);
    31. unsigned long pulseStarts[NUMBER_OF_PULSE_PINS];
    32. unsigned long pulseLength = 500;
    33.  
    34. void setup()
    35. {
    36.   //Serial.begin (9600);
    37.   Serial.begin (115200);
    38.   Serial.setTimeout(13); //Added today Sun Nov 22 ( not sure if this is needed? )
    39.  
    40.   pinMode(buttonRight, INPUT); //Defines Pin Mode
    41.   pinMode(buttonLeft, INPUT);
    42.  
    43.   digitalWrite(buttonRight, HIGH);
    44.   digitalWrite(buttonLeft, HIGH);
    45.  
    46.   pinMode(wLed, OUTPUT);
    47.   pinMode(rLed, OUTPUT);
    48.   pinMode(rLed2, OUTPUT);
    49.   pinMode(yLed, OUTPUT);
    50.   pinMode(gLed, OUTPUT);
    51.   pinMode(gLed2, OUTPUT);
    52.   pinMode(gLed3, OUTPUT);
    53.   pinMode(bLed, OUTPUT);
    54.   pinMode(bLed2, OUTPUT);
    55.   digitalWrite(wLed, LOW);
    56.   digitalWrite(rLed, LOW);
    57.   digitalWrite(rLed2, LOW);
    58.   digitalWrite(yLed, LOW);
    59.   digitalWrite(gLed, LOW);
    60.   digitalWrite(gLed2, LOW);
    61.   digitalWrite(gLed3, LOW);
    62.   digitalWrite(bLed, LOW);
    63.   digitalWrite(bLed2, LOW);
    64.  
    65.   for (int p = 0; p < NUMBER_OF_PULSE_PINS; p++)
    66.   {
    67.     pinMode(pulsePins[p], OUTPUT);
    68.     digitalWrite(pulsePins[p], LOW);
    69.   }
    70. }
    71.  
    72. void loop()
    73. {
    74.  
    75.  
    76.   // read the new light value (in range 0..1023):
    77.      int sensorValue = analogRead(lightSensorPin);
    78.      // if the value changed by 10
    79.      if(lightSensorValue - sensorValue > 10 || sensorValue - lightSensorValue > 10){
    80.          lightSensorValue = sensorValue; // save the new value
    81.          float p = lightSensorValue * (100.0 / 1023.0);    // make the value to range 0..100
    82.          // the Parentheses may be for compiler optimization idk
    83.          Serial.println(p); // send it to unity
    84.      }
    85.  
    86.   bRS = digitalRead(buttonRight);
    87.   bLS = digitalRead(buttonLeft);
    88.  
    89.  
    90.   if (Serial.available())              //if serial data is available
    91.   {
    92.  
    93.    
    94.    
    95.     int lf = 10;
    96.  
    97.     myChar = Serial.read();             //read one character from serial
    98.     if (myChar == 'r')                  //if it is an r
    99.     {
    100.       digitalWrite(rLed, !digitalRead(rLed));  //Oil Slick Toggle
    101.     }
    102.    
    103.     if (myChar == 'b')
    104.     {
    105.       digitalWrite(bLed, !digitalRead(bLed)); //Surveillance Mode Toggle
    106.     }
    107.  
    108.     if (myChar == 'y')
    109.     {
    110.       digitalWrite(yLed, !digitalRead(yLed)); //Movie Player Toggle
    111.     }
    112.  
    113.     if (myChar == 'g')
    114.     {
    115.       digitalWrite(gLed, !digitalRead(gLed)); //Auto Phone Toggle
    116.     }
    117.  
    118.     if (myChar == '1')
    119.     {
    120.       digitalWrite(bLed2, !digitalRead(bLed2)); //Scanner Toggle
    121.     }
    122.  
    123.     if (myChar == 'f')
    124.     {
    125.       digitalWrite(gLed2, !digitalRead(gLed2)); //Fog Lights Toggle
    126.     }
    127.  
    128.     if (myChar == 'h')
    129.     {
    130.       digitalWrite(gLed3, !digitalRead(gLed3)); //Head Lights Toggle
    131.     }
    132.  
    133.     if (myChar == 'H')
    134.     {
    135.       digitalWrite(wLed, !digitalRead(wLed)); //High Beams Toggle
    136.     }
    137.  
    138.  
    139.     //Rear Hatch Popper
    140.     for (int p = 0; p < NUMBER_OF_PULSE_PINS; p++)
    141.     {
    142.       if (myChar == pulseTriggers[p])
    143.       {
    144.         pulseStarts[p] = millis();  //save the time of receipt
    145.         digitalWrite(pulsePins[p], HIGH);
    146.       }
    147.     }
    148.  
    149.  
    150.     //Grappling Hook Launch
    151.     for (int q = 0; q < NUMBER_OF_PULSE_PINS; q++)
    152.     {
    153.       if (myChar == pulseTriggers[q])
    154.       {
    155.         pulseStarts[q] = millis();  //save the time of receipt
    156.         digitalWrite(pulsePins[q], HIGH);
    157.       }
    158.     }
    159.  
    160.  
    161.     //Auto Doors Right Pulse
    162.     for (int R = 0; R < NUMBER_OF_PULSE_PINS; R++)
    163.     {
    164.       if (myChar == pulseTriggers[R])
    165.       {
    166.         pulseStarts[R] = millis();  //save the time of receipt
    167.         digitalWrite(pulsePins[R], HIGH);
    168.       }
    169.     }
    170.  
    171.  
    172.     //Auto Doors Left Pulse
    173.     for (int L = 0; L < NUMBER_OF_PULSE_PINS; L++)
    174.     {
    175.       if (myChar == pulseTriggers[L])
    176.       {
    177.         pulseStarts[L] = millis();  //save the time of receipt
    178.         digitalWrite(pulsePins[L], HIGH);
    179.       }
    180.     }
    181.   }
    182.  
    183.   //the following code runs each time through loop()
    184.   for (int p = 0; p < NUMBER_OF_PULSE_PINS; p++)
    185.   {
    186.     if (millis() - pulseStarts[p] >= pulseLength)  //has the pin been HIGH long enough ?
    187.     {
    188.       digitalWrite(pulsePins[p], LOW);   //take the pulse pin LOW
    189.     }
    190.   }
    191.  
    192.   for (int q = 0; q < NUMBER_OF_PULSE_PINS; q++)
    193.   {
    194.     if (millis() - pulseStarts[q] >= pulseLength)  //has the pin been HIGH long enough ?
    195.     {
    196.       digitalWrite(pulsePins[q], LOW);   //take the pulse pin LOW
    197.     }
    198.   }
    199.  
    200.   if(bLS == HIGH && bRS == HIGH) // If both buttons are NOT pressed
    201.   {
    202.    Serial.println("0");
    203.   }
    204.  
    205.   if(bLS == LOW && bRS == HIGH) // If only the LEFT button is pressed
    206.   {
    207.     Serial.println("4");
    208.   }
    209.  
    210.   if(bLS == HIGH && bRS == LOW) // If only the RIGHT button is pressed
    211.   {
    212.     Serial.println("5");
    213.   }
    214.     Serial.flush();
    215.     delay(20);
    216.  
    217. }
     
  7. Polymorphik

    Polymorphik

    Joined:
    Jul 25, 2014
    Posts:
    599
    Sorry for the late reply.

    So yeah it is a lot of code but in the end its flexable as you can use it to capture states of the button just like you would using Unity's Input class. Basically the code I wrote is suppose to be like UnityEngine.Input but this will listen for inputs on the arduino serial buffer. Now why would you want to do this? Well, first to centralize the logic for input, you dont want each script that you may need in the future to have to keep track of the last time a button was pressed. This would have repeatative code and will be less flexable.

    The reason the clip keeps playing is because you are basically saying this.

    If ButtonPressed
    DoStuff

    the DoStuff is your animation and audio clip firing. The only time you want this to happen is when the button was first pressed. Now, you did say its suppose to act like a turn signal, in that case you would want the audio clip to play every so often like a clicker noise in an actual car. In that case you would need to have a delay between audio clicks and something to keep track of the time elapsed since the last click.

    Using the wrapper you can then just query like so
    Code (CSharp):
    1. /// <summary>
    2. /// Use case.
    3. /// </summary>
    4. public class Clicker : MonoBehaviour {
    5.     [SerializeField] float m_rate = 2.0F; // 2 clicks per second.
    6.  
    7.     float m_elapsedTime = 0.0F;
    8.  
    9.     void Update() {
    10.         // Check when the button was first pressed.
    11.         if(AInputState.Down == Wrapper.GetState(AInput.Left)) {
    12.             this.Click();
    13.         }
    14.  
    15.         // Repeat clicker noise every so often as long as the button
    16.         // is being pressed.
    17.         if(AInputState.Pressed == Wrapper.GetState(AInput.Left)) {
    18.             float delay = 60.0F / this.m_rate; // Delay between click rates.
    19.  
    20.             // If the elapsed time is greater than or equal to the delay
    21.             // between clicks. Invoke Click();
    22.             if(this.m_elapsedTime >= delay) {
    23.                 this.Click(); // Invoke Click
    24.                 this.m_elapsedTime = 0.0F; // Reset elapsed time
    25.             } else {
    26.                 // Increment elapsed time.
    27.                 this.m_elapsedTime += Time.deltaTime;
    28.             }
    29.         }
    30.  
    31.         // Reset the elapsed time when the button has been released.
    32.         if(AInputState.Up == Wrapper.GetState(AInput.Left)) {
    33.             this.m_elapsedTime = 0.0F; // Reset elapsed time.
    34.         }
    35.     }
    36.  
    37.     void Click() {
    38.         // Play Audio and animation
    39.     }
    40. }
    See how easy and clean it can be done if you first write a wrapper to listen for inputs? I am calling the class Wrapper but you can call it w/e you want. The sole purpose for Wrapper is to just listen for inputs and keep tracks of their states IE IsDown, IsPressed, IsUp.
     
  8. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Thanks Polymorphik,
    I did manage to solve one issue yesterday, lol what a way to spend Christmas ;)
    I made a couple of new game objects to hold the sounds for when the Bar Graph (GUI) graphics activate they set active the sound objects for Up sound i.e. bar graph on and down sound i.e. bar graph off.
    The sound objects are set to play the sound on awake and not to loop so they will only play the sound once.
    It looks like what you are doing here is very different from how I have my project set up so not being much of a code guy I'm having a hard time trying to figure out how to integrate any of what you have posted.
    I'll upload a video to show what I mean.

    My LDR sensor is not working as it should though. I'm not much of a code guy so you'll have to be patient with me, eventually I'll get it but there is a lot about this stuff I'm not very familiar with. ;)

    this project will actually be hooked up to my K.I.T.T. in the garage so the turn signal switches will basically replace those little micro buttons most likely through an optocoupler or Relay. The theory is sound so it should work on that end. ;)

    My Arduino code is the same as in my last post, I did change this part of my Unity code from my last post.

    Code (CSharp):
    1. void DirectionArrow(int buttonStatus)
    2.     //void DirectionArrow(int Direction)
    3.     {
    4.      
    5.     switch (buttonStatus)
    6.     {
    7.         //ON Button  State
    8.         case 0:
    9.             //deactivate Left Direction Arrow
    10.             SystemGuidanceManagerScript WAO = FindObjectOfType<SystemGuidanceManagerScript>();
    11.             WAO.WestArrowOff ();
    12.  
    13.             SystemGuidanceManagerScript EAO = FindObjectOfType<SystemGuidanceManagerScript>();
    14.             EAO.EastArrowOff();
    15.  
    16.             SystemGuidanceManagerScript SFXOff = FindObjectOfType<SystemGuidanceManagerScript>();
    17.             SFXOff.TopIndicatorOff();
    18.  
    19.             SystemGuidanceManagerScript BGSOff = FindObjectOfType<SystemGuidanceManagerScript>();
    20.             BGSOff.BarLEDsSounderOff();
    21.             break;
    22.  
    23.         case 4:
    24.             //Activate Left Direction Arrow Indicator
    25.             SystemGuidanceManagerScript WA = FindObjectOfType<SystemGuidanceManagerScript>();
    26.             WA.WestArrow();
    27.             SystemGuidanceManagerScript WBSOn = FindObjectOfType<SystemGuidanceManagerScript>();
    28.             WBSOn.BarLEDsSounderOn();
    29.             break;
    30.  
    31.         case 5:
    32.             //Activate Right Direction Arrow Indicator
    33.             SystemGuidanceManagerScript EA = FindObjectOfType<SystemGuidanceManagerScript>();
    34.             EA.EastArrow();
    35.             SystemGuidanceManagerScript EBSOn = FindObjectOfType<SystemGuidanceManagerScript>();
    36.             EBSOn.BarLEDsSounderOn();
    37.             break;
    38.     }
    39.          
    40.     }
    I'll bet my Script on the System guidance screen is a real piece of work though, it confuses the hell out of me at the best of time ;)

    Here is that nasty bit of business ;)
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5.  
    6. public class SystemGuidanceManagerScript : MonoBehaviour {
    7.  
    8.  
    9.     float volume = 0.3f; //Clip Volume Setting
    10.  
    11.     //Audio Clip References
    12.     //public AudioClip BarGraphInFX;
    13.     //public AudioClip BarGraphOutFX;
    14.  
    15.     //LED Bargraph Sounder Objects
    16.     public GameObject BarLEDsSounderUp;
    17.     public GameObject BarLEDsSounderDown;
    18.  
    19.     //LED Light Animation Game Objects
    20.     public GameObject ledLightsN;
    21.     public GameObject ledLightsS;
    22.     public GameObject ledLightsW;
    23.     public GameObject ledLightsE;
    24.  
    25.     //Arrow Indicator Animation Game Objects
    26.     public GameObject ledNarrow;
    27.     public GameObject ledSarrow;
    28.     public GameObject ledWarrow;
    29.     public GameObject ledEarrow;
    30.  
    31.     //Top LED Indicator Game Object
    32.     public GameObject Top_LED_Indicator;
    33.  
    34.     //Top Indicator Animation
    35.     public Animator TopIndicatorLED;
    36.     public AudioSource IndicatorsFX;
    37.     private Animator animTopIndLED;
    38.  
    39.     //North Animations
    40.     public Animator LEDlightsN;
    41.     public Animator IndicatorArrowN;
    42.  
    43.     //North Animator Reference
    44.     private Animator animN;
    45.     private Animator animNarrow;
    46.  
    47.     //South Animations
    48.     public Animator LEDlightsS;
    49.     public Animator IndicatorArrowS;
    50.  
    51.     //South Animator Reference
    52.     private Animator animS;
    53.     private Animator animSarrow;
    54.  
    55.     //West Animations
    56.     public Animator LEDlightsW;
    57.     public Animator IndicatorArrowW;
    58.  
    59.     //West Animator Reference
    60.     private Animator animW;
    61.     private Animator animWarrow;
    62.  
    63.     //East Animations
    64.     public Animator LEDlightsE;
    65.     public Animator IndicatorArrowE;
    66.  
    67.     //East Animator Reference
    68.     private Animator animE;
    69.     private Animator animEarrow;
    70.  
    71.  
    72.  
    73.     void Start ()
    74.     {
    75.         //BarGraph Sounder Objects
    76.         BarLEDsSounderUp.SetActive(false);
    77.         BarLEDsSounderDown.SetActive(false);
    78.  
    79.         //Top LED Indicator
    80.         animTopIndLED = TopIndicatorLED.GetComponent<Animator>();
    81.         animTopIndLED.enabled = false;
    82.         IndicatorsFX.enabled = false;
    83.         Top_LED_Indicator.SetActive(false);
    84.  
    85.         //NORTH
    86.         animN = LEDlightsN.GetComponent<Animator>();
    87.         animN.enabled = false;
    88.  
    89.         animNarrow = IndicatorArrowN.GetComponent<Animator>();
    90.         animNarrow.enabled = false;
    91.  
    92.  
    93.         //SOUTH
    94.         animS = LEDlightsS.GetComponent<Animator> ();
    95.         animS.enabled = false;
    96.  
    97.         animSarrow = IndicatorArrowS.GetComponent<Animator> ();
    98.         animSarrow.enabled = false;
    99.  
    100.         //WEST
    101.         animW = LEDlightsW.GetComponent<Animator> ();
    102.         animW.enabled = false;
    103.  
    104.         animWarrow = IndicatorArrowW.GetComponent<Animator> ();
    105.         animWarrow.enabled = false;
    106.  
    107.         //EAST
    108.         animE = LEDlightsE.GetComponent<Animator> ();
    109.         animE.enabled = false;
    110.  
    111.         animEarrow = IndicatorArrowE.GetComponent<Animator> ();
    112.         animEarrow.enabled = false;
    113.     }
    114.  
    115.  
    116.     //Turn On Top LED Indicator
    117.     public void TopIndicatorOn (){
    118.         //animTopIndLED = TopIndicatorLED.GetComponent<Animator>();
    119.         animTopIndLED.enabled = true;
    120.         IndicatorsFX.enabled = true;
    121.         Top_LED_Indicator.SetActive (true);
    122.     }
    123.  
    124.     //Turn Off Top LED Indicator
    125.     public void TopIndicatorOff (){
    126.         //animTopIndLED = TopIndicatorLED.GetComponent<Animator>();
    127.         animTopIndLED.enabled = false;
    128.         IndicatorsFX.enabled = false;
    129.         Top_LED_Indicator.SetActive (false);
    130.     }
    131.  
    132.     //BarGraph Sounder On
    133.     public void BarLEDsSounderOn (){
    134.         BarLEDsSounderUp.SetActive (true);
    135.         BarLEDsSounderDown.SetActive (false);
    136.     }
    137.     //BarGraph Sounder Off
    138.     public void BarLEDsSounderOff (){
    139.         BarLEDsSounderUp.SetActive (false);
    140.         BarLEDsSounderDown.SetActive (true);
    141.     }
    142.  
    143.  
    144.     //Up Arrow North
    145.     public void NorthArrow (){
    146.         //if (Input.GetKeyDown (KeyCode.UpArrow)) {
    147.         animTopIndLED.enabled = true;
    148.         IndicatorsFX.enabled = true;
    149.         Top_LED_Indicator.SetActive (true);
    150.         animW.enabled = false;
    151.         animE.enabled = false;
    152.         animNarrow.enabled = true;
    153.         animSarrow.enabled = false;
    154.         animWarrow.enabled = false;
    155.         animEarrow.enabled = false;
    156.         GetComponent<Animator> ();
    157.         animN.enabled = true;
    158.         animN.Play ("GuidanceBarGraph_N_ani");
    159.         //GetComponent<AudioSource> ().PlayOneShot (BarGraphInFX, volume);
    160.         animNarrow.Play ("GuidanceInidicatorsN_ani");
    161.         animS.Play ("GuidanceBarGraph_SOff_ani");
    162.         ledSarrow.SetActive (false);
    163.         ledWarrow.SetActive (false);
    164.         ledEarrow.SetActive (false);
    165.         ledNarrow.SetActive (true);
    166.  
    167.         ledLightsE.SetActive (false);
    168.         ledLightsW.SetActive (false);
    169.  
    170.         ledLightsN.SetActive (true);
    171.     }
    172.  
    173.  
    174.  
    175.         //Up Arrow North Off
    176. public void NorthArrowOff(){
    177.         //if (Input.GetKeyUp (KeyCode.UpArrow)) {
    178.             animN.Play ("GuidanceBarGraph_NOff_ani");
    179.             //GetComponent<AudioSource>().PlayOneShot(BarGraphOutFX, volume);
    180.             ledNarrow.SetActive(false);
    181.             IndicatorsFX.enabled = false;
    182.             animTopIndLED.enabled = false;
    183.             Top_LED_Indicator.SetActive(false);
    184.         }
    185.  
    186.  
    187.  
    188.         //Down Arrow South
    189. public void SouthArrow(){
    190.         //if (Input.GetKeyDown (KeyCode.DownArrow)) {
    191.             animTopIndLED.enabled = true;
    192.             IndicatorsFX.enabled = true;
    193.             Top_LED_Indicator.SetActive(true);
    194.             animW.enabled = false;
    195.             animE.enabled = false;
    196.             animNarrow.enabled = false;
    197.             animSarrow.enabled = true;
    198.             animWarrow.enabled = false;
    199.             animEarrow.enabled = false;
    200.             GetComponent<Animator> ();
    201.             animS.enabled = true;
    202.             animS.Play ("GuidanceBarGraph_S_ani");
    203.             //GetComponent<AudioSource>().PlayOneShot(BarGraphInFX, volume);
    204.             animSarrow.Play ("GuidanceInidicatorsS_ani");
    205.             animN.Play ("GuidanceBarGraph_NOff_ani");
    206.             ledNarrow.SetActive(false);
    207.             ledWarrow.SetActive(false);
    208.             ledEarrow.SetActive(false);
    209.             ledSarrow.SetActive(true);
    210.  
    211.             ledLightsE.SetActive(false);
    212.             ledLightsW.SetActive(false);
    213.  
    214.             ledLightsS.SetActive(true);
    215.         }
    216.  
    217.  
    218.         //Down Arrow South Off
    219. public void SouthArrowOff(){
    220.         //if (Input.GetKeyUp (KeyCode.DownArrow)) {
    221.             animS.Play ("GuidanceBarGraph_SOff_ani");
    222.             //GetComponent<AudioSource>().PlayOneShot(BarGraphOutFX, volume);
    223.             ledSarrow.SetActive(false);
    224.             IndicatorsFX.enabled = false;
    225.             animTopIndLED.enabled = false;
    226.             Top_LED_Indicator.SetActive(false);
    227.         }
    228.          
    229.  
    230.  
    231.         //Left Arrow West
    232. public void WestArrow(){
    233.         //if (Input.GetKeyDown (KeyCode.LeftArrow)) {
    234.             //BarGraph Sounder Objects
    235.             //BarLEDsSounderUp.SetActive(true);
    236.             //BarLEDsSounderDown.SetActive(false);
    237.          
    238.             animTopIndLED.enabled = true;
    239.             IndicatorsFX.enabled = true;
    240.             Top_LED_Indicator.SetActive(true);
    241.             animW.enabled = true;
    242.             //animE.enabled = true;
    243.             animNarrow.enabled = false;
    244.             animSarrow.enabled = false;
    245.             animWarrow.enabled = true;
    246.             animEarrow.enabled = false;
    247.             GetComponent<Animator> ();
    248.             animN.enabled = false;
    249.             animW.Play ("GuidanceBarGraph_W_ani");
    250.             animWarrow.Play ("GuidanceInidicatorsW_ani");
    251.             animE.Play ("GuidanceBarGraph_EOff_ani");
    252.             ledEarrow.SetActive(false);
    253.             ledNarrow.SetActive(false);
    254.             ledSarrow.SetActive(false);
    255.             ledWarrow.SetActive(true);
    256.  
    257.             ledLightsN.SetActive(false);
    258.             ledLightsS.SetActive(false);
    259.  
    260.             ledLightsW.SetActive(true);
    261.         }
    262.  
    263.         //Left Arrow West Off
    264. public void WestArrowOff(){
    265.         //if (Input.GetKeyUp (KeyCode.LeftArrow)) {
    266.             //BarGraph Sounder Objects
    267.             //BarLEDsSounderUp.SetActive(false);
    268.             //BarLEDsSounderDown.SetActive(true);
    269.  
    270.             animW.Play ("GuidanceBarGraph_WOff_ani");
    271.             ledWarrow.SetActive(false);
    272.             IndicatorsFX.enabled = false;
    273.             animTopIndLED.enabled = false;
    274.             Top_LED_Indicator.SetActive(false);
    275.         }
    276.  
    277.  
    278.         //Right Arrow East
    279. public void EastArrow(){
    280.         //if (Input.GetKeyDown (KeyCode.RightArrow)) {
    281.             //BarGraph Sounder Objects
    282.             //BarLEDsSounderUp.SetActive(true);
    283.             //BarLEDsSounderDown.SetActive(false);
    284.  
    285.             animTopIndLED.enabled = true;
    286.             IndicatorsFX.enabled = true;
    287.             Top_LED_Indicator.SetActive(true);
    288.             animE.enabled = true;
    289.             animNarrow.enabled = false;
    290.             animSarrow.enabled = false;
    291.             animWarrow.enabled = false;
    292.             animEarrow.enabled = true;
    293.             GetComponent<Animator> ();
    294.             animS.enabled = false;
    295.             animE.Play ("GuidanceBarGraph_E_ani");
    296.             animEarrow.Play ("GuidanceInidicatorsS_ani");
    297.             animW.Play ("GuidanceBarGraph_WOff_ani");
    298.             ledWarrow.SetActive(false);
    299.             ledSarrow.SetActive(false);
    300.             ledNarrow.SetActive(false);
    301.             ledEarrow.SetActive(true);
    302.  
    303.             ledLightsN.SetActive(false);
    304.             ledLightsS.SetActive(false);
    305.  
    306.             ledLightsE.SetActive(true);
    307.         }
    308.  
    309.  
    310.         //Right Arrow East Off
    311. public void EastArrowOff(){
    312.         //if (Input.GetKeyUp (KeyCode.RightArrow)) {
    313.             //BarGraph Sounder Objects
    314.             //BarLEDsSounderUp.SetActive(false);
    315.             //BarLEDsSounderDown.SetActive(true);
    316.  
    317.             animE.Play ("GuidanceBarGraph_EOff_ani");
    318.             ledEarrow.SetActive(false);
    319.             IndicatorsFX.enabled = false;
    320.             animTopIndLED.enabled = false;
    321.             Top_LED_Indicator.SetActive(false);
    322.         }
    323.  
    324.  
    325.  
    326.  
    327.     //Trajectory Gude Scene Loads
    328.     public void  GoTrajectoryScreen(){
    329.         StartCoroutine(LoadAfterDelayT1("TrajectoryGuideScreen"));
    330.     }
    331.  
    332.     IEnumerator LoadAfterDelayT1(string levelName){
    333.         yield return new WaitForSeconds(0.5f); // wait 1 seconds
    334.         Application.LoadLevel(levelName);
    335.      
    336.     }
    337.  
    338.     //Quit Button
    339.     public void  GoQuit(){
    340.         StartCoroutine(LoadQuit("MainScreen"));
    341.     }
    342.  
    343.     IEnumerator LoadQuit(string levelMain){
    344.         yield return new WaitForSeconds(0.5f); // wait time
    345.         Application.LoadLevel(levelMain);
    346.      
    347.     }
    348. }
    349.  
    Here is my latest video that demos the changes I have made using some of ideas you had posted.

     
    Last edited: Dec 27, 2015
  9. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    I still can't seem to wrap my head around what is going on here with this thing. I'm not sure if it's the Arduino side that is the problem or if it's the Unity code that is giving me the issues.
    From experimenting it seems as if because the serial is receiving "0" all of the time from the buttons "UP State" that this is somehow conflicting with the LDR sensor values being also read in through the serial port. Maybe the two devices just can't be used on one Arduino board which really sucks because I was hoping to be able to add a temperature sensor as well.
     
  10. Polymorphik

    Polymorphik

    Joined:
    Jul 25, 2014
    Posts:
    599
    Hmm...I have not yet used an arduino but is there a way to change the output or is it a harcoded value from the manufacture?
     
  11. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Well, I'm not sure, I do know that the LDR sensor needs to send it's data in the form of number values but button inputs I believe can be letter or characters, Atlas FROM Unity to Arduino I'm simply sending a Character through the serial port and then reading that into the Arduino to turn on LEDs on my breadboard.... eventually these will be Optocoupler activated relays.
    If you look at my Unity Sending script I posted you'll see how the data is sent to the Arduino and how the Sending script received the data from the Arduino for the LDR sensor. ;)

    I'm not very good at code so I have a hard time with new code, I'm much better at looking at working samples and figuring out from there what is doing what and then how to implement that into what I want to do.
     
  12. Polymorphik

    Polymorphik

    Joined:
    Jul 25, 2014
    Posts:
    599
    For buttons switch the receiving to char. Chars are only 2 bytes so comparing chars is not expensive. If you do decide to use the wrapper you can cast the char to its int equivalent so you can use Enums instead. I was looking the arduino home page and man...I should REALLY get one so many cool things you can do with it. And the code is in C++ so its right in my own backyard haha.
     
    KnightRiderGuy likes this.
  13. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Yup, it's one of the reasons I chose to go with Unity for my Knight Rider dash software project because of it's integration of Arduino into Unity and yup, there are so many cool things I have seen people do with it.
    The Arduino's are inexpensive too, I got mine on eBay for about 6 bucks, can't beat that ;)
     
  14. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Ok I'm getting a little further along, I found if I do this with my Arduino code then my buttons states are remembered and it does not continually send a 0 through the Serial Port. Near the bottom is my Buttons sending stuff setup and what not is near the top.

    Code (CSharp):
    1.  
    2. int lightSensorPin = A0; //Define the Light Sensor Pin
    3. int lightSensorValue = 0;
    4.  
    5. //int lightLevel = analogRead(0);
    6. //int threshold = 250;
    7. //int range = 50;
    8.  
    9. //Defines Our Button Pins
    10. const int buttonRight = A1;
    11. const int buttonLeft = A2;
    12.  
    13. // Variable to hold the state of the buttons
    14. int bRS, bLS; //ButtonRight and ButtonLeft states status holders
    15.  
    16.  
    17. //Sets Pin number LED is conneted too
    18. const byte rLed = 12;
    19. const byte rLed2 = 1;
    20. const byte yLed = 11;
    21. const byte gLed = 10;
    22. const byte gLed2 = 5;
    23. const byte gLed3 = 4;
    24. const byte wLed = 3;
    25. const byte bLed = 2;
    26. const byte bLed2 = 13;
    27.  
    28. char myChar;         //changed the name of this variable because they are not all colurs now
    29. const byte pulsePins[] = {6, 7, 8, 9};  //pins for a pulse output
    30. char pulseTriggers[] = {'p', 'q','R','L'};
    31. const int NUMBER_OF_PULSE_PINS = sizeof(pulsePins);
    32. unsigned long pulseStarts[NUMBER_OF_PULSE_PINS];
    33. unsigned long pulseLength = 500;
    34.  
    35. int buttonStateR = 0;
    36. int lastButtonStateR = 0;
    37.  
    38. int buttonStateL = 0;
    39. int lastButtonStateL = 0;
    40. int buttonPushCounter = 0;
    41.  
    42. void setup()
    43. {
    44.   //Serial.begin (9600);
    45.   Serial.begin (115200);
    46.   Serial.setTimeout(13); //Added today Sun Nov 22 ( not sure if this is needed? )
    47.  
    48.   pinMode(buttonRight, INPUT); //Defines Pin Mode
    49.   pinMode(buttonLeft, INPUT);
    50.  
    51.   digitalWrite(buttonRight, HIGH);
    52.   digitalWrite(buttonLeft, HIGH);
    53.  
    54.   pinMode(wLed, OUTPUT);
    55.   pinMode(rLed, OUTPUT);
    56.   pinMode(rLed2, OUTPUT);
    57.   pinMode(yLed, OUTPUT);
    58.   pinMode(gLed, OUTPUT);
    59.   pinMode(gLed2, OUTPUT);
    60.   pinMode(gLed3, OUTPUT);
    61.   pinMode(bLed, OUTPUT);
    62.   pinMode(bLed2, OUTPUT);
    63.   digitalWrite(wLed, LOW);
    64.   digitalWrite(rLed, LOW);
    65.   digitalWrite(rLed2, LOW);
    66.   digitalWrite(yLed, LOW);
    67.   digitalWrite(gLed, LOW);
    68.   digitalWrite(gLed2, LOW);
    69.   digitalWrite(gLed3, LOW);
    70.   digitalWrite(bLed, LOW);
    71.   digitalWrite(bLed2, LOW);
    72.  
    73.   for (int p = 0; p < NUMBER_OF_PULSE_PINS; p++)
    74.   {
    75.     pinMode(pulsePins[p], OUTPUT);
    76.     digitalWrite(pulsePins[p], LOW);
    77.   }
    78. }
    79.  
    80. void loop()
    81. {
    82.  
    83.  
    84.   // read the new light value (in range 0..1023):
    85.      int sensorValue = analogRead(lightSensorPin);
    86.      // if the value changed by 10
    87.      if(lightSensorValue - sensorValue > 10 || sensorValue - lightSensorValue > 10){
    88.          lightSensorValue = sensorValue; // save the new value
    89.          float p = lightSensorValue * (100.0 / 1023.0);    // make the value to range 0..100
    90.          // the Parentheses may be for compiler optimization idk
    91.          Serial.println(p); // send it to unity
    92.      }
    93.  
    94.   //bRS = digitalRead(buttonRight);
    95.   //bLS = digitalRead(buttonLeft);
    96.  
    97.  
    98.   if (Serial.available())              //if serial data is available
    99.   {
    100.  
    101.    
    102.    
    103.     int lf = 10;
    104.  
    105.     myChar = Serial.read();             //read one character from serial
    106.     if (myChar == 'r')                  //if it is an r
    107.     {
    108.       digitalWrite(rLed, !digitalRead(rLed));  //Oil Slick Toggle
    109.     }
    110.    
    111.     if (myChar == 'b')
    112.     {
    113.       digitalWrite(bLed, !digitalRead(bLed)); //Surveillance Mode Toggle
    114.     }
    115.  
    116.     if (myChar == 'y')
    117.     {
    118.       digitalWrite(yLed, !digitalRead(yLed)); //Movie Player Toggle
    119.     }
    120.  
    121.     if (myChar == 'g')
    122.     {
    123.       digitalWrite(gLed, !digitalRead(gLed)); //Auto Phone Toggle
    124.     }
    125.  
    126.     if (myChar == 's')
    127.     {
    128.       digitalWrite(bLed2, !digitalRead(bLed2)); //Scanner Toggle
    129.     }
    130.  
    131.     if (myChar == 'f')
    132.     {
    133.       digitalWrite(gLed2, !digitalRead(gLed2)); //Fog Lights Toggle
    134.     }
    135.  
    136.     if (myChar == 'h')
    137.     {
    138.       digitalWrite(gLed3, !digitalRead(gLed3)); //Head Lights Toggle
    139.     }
    140.  
    141.     if (myChar == 'H')
    142.     {
    143.       digitalWrite(wLed, !digitalRead(wLed)); //High Beams Toggle
    144.     }
    145.  
    146.  
    147.     //Rear Hatch Popper
    148.     for (int p = 0; p < NUMBER_OF_PULSE_PINS; p++)
    149.     {
    150.       if (myChar == pulseTriggers[p])
    151.       {
    152.         pulseStarts[p] = millis();  //save the time of receipt
    153.         digitalWrite(pulsePins[p], HIGH);
    154.       }
    155.     }
    156.  
    157.  
    158.     //Grappling Hook Launch
    159.     for (int q = 0; q < NUMBER_OF_PULSE_PINS; q++)
    160.     {
    161.       if (myChar == pulseTriggers[q])
    162.       {
    163.         pulseStarts[q] = millis();  //save the time of receipt
    164.         digitalWrite(pulsePins[q], HIGH);
    165.       }
    166.     }
    167.  
    168.  
    169.     //Auto Doors Right Pulse
    170.     for (int R = 0; R < NUMBER_OF_PULSE_PINS; R++)
    171.     {
    172.       if (myChar == pulseTriggers[R])
    173.       {
    174.         pulseStarts[R] = millis();  //save the time of receipt
    175.         digitalWrite(pulsePins[R], HIGH);
    176.       }
    177.     }
    178.  
    179.  
    180.     //Auto Doors Left Pulse
    181.     for (int L = 0; L < NUMBER_OF_PULSE_PINS; L++)
    182.     {
    183.       if (myChar == pulseTriggers[L])
    184.       {
    185.         pulseStarts[L] = millis();  //save the time of receipt
    186.         digitalWrite(pulsePins[L], HIGH);
    187.       }
    188.     }
    189.   }
    190.  
    191.   //the following code runs each time through loop()
    192.   for (int p = 0; p < NUMBER_OF_PULSE_PINS; p++)
    193.   {
    194.     if (millis() - pulseStarts[p] >= pulseLength)  //has the pin been HIGH long enough ?
    195.     {
    196.       digitalWrite(pulsePins[p], LOW);   //take the pulse pin LOW
    197.     }
    198.   }
    199.  
    200.   for (int q = 0; q < NUMBER_OF_PULSE_PINS; q++)
    201.   {
    202.     if (millis() - pulseStarts[q] >= pulseLength)  //has the pin been HIGH long enough ?
    203.     {
    204.       digitalWrite(pulsePins[q], LOW);   //take the pulse pin LOW
    205.     }
    206.   }
    207.  
    208.   // read the pushbutton input pin
    209.   buttonStateR = digitalRead(buttonRight);
    210.  
    211.   //compare the buttonState to its previous state
    212.   if (buttonStateR != lastButtonStateR){
    213.     // if the state has changed, increment the counter
    214.     if (buttonStateR == LOW){
    215.       // if the current state is HIGH then the button went from off to on
    216.       buttonPushCounter++;
    217.       Serial.println(1);
    218.       Serial.print("number of button pushes: ");
    219.       Serial.println(buttonPushCounter);
    220.     }else{
    221.       // if the current state is LOW then the button went from on to off
    222.       Serial.println(0);
    223.     }
    224.     // Delay  little bit to avoid bouncing
    225.     delay(50);
    226.   }
    227.     // save the current state as the last state for the next time through loop
    228.       lastButtonStateR = buttonStateR;
    229.  
    230.  
    231.    // read the pushbutton input pin
    232.   buttonStateL = digitalRead(buttonLeft);
    233.  
    234.   //compare the buttonState to its previous state
    235.   if (buttonStateL != lastButtonStateL){
    236.     // if the state has changed, increment the counter
    237.     if (buttonStateL == LOW){
    238.       // if the current state is HIGH then the button went from off to on
    239.       buttonPushCounter++;
    240.       Serial.println(2);
    241.       Serial.print("number of button pushes: ");
    242.       Serial.println(buttonPushCounter);
    243.     }else{
    244.       // if the current state is LOW then the button went from on to off
    245.       Serial.println(0);
    246.     }
    247.     // Delay  little bit to avoid bouncing
    248.     delay(50);
    249.   }
    250.   // save the current state as the last state for the next time through loop
    251.   lastButtonStateL = buttonStateL;
    252.    
    253.  
    254. }

    My Unity Code I tweaked and played around with a little more, I found if I alter it this way my light sensor works now but my button inputs are a little slow and sometimes non responsive.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4. using System.IO.Ports;
    5. using System.Threading;
    6.  
    7.  
    8. public class Sending : MonoBehaviour {
    9.  
    10.  
    11.     //int sysHour = System.DateTime.Now.Hour;
    12.    
    13.     //Random Clips
    14.     public AudioClip[] BrightnessAudioClips;
    15.     public AudioClip[] DarknessAudioClips;
    16.     public AudioClip[] AnnoyedAudioClips;
    17.  
    18.     //DTMF Tones
    19.     public AudioClip DTMFtone01;
    20.     public AudioClip DTMFtone02;
    21.     public AudioClip DTMFtone06;
    22.     public AudioClip DTMFtone08;
    23.     public AudioSource source;
    24.  
    25.     //UI Text Reference
    26.     //public Text MessageCentreText;
    27.  
    28.     //_isPlayingSound is true when a sound is currently playing - just as the name suggests.
    29.     private bool _isPlayingSound;
    30.  
    31.     const float sliderChangeVelocity = 0.5f;
    32.     private float desiredSliderValue;
    33.  
    34.     public GameObject LightSlider;
    35.     public Slider slider;
    36.     Slider lightSlider;
    37.     public static Sending sending;
    38.  
    39.     //public static SerialPort sp = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
    40.     public static SerialPort sp = new SerialPort("/dev/cu.wchusbserial1420", 115200, Parity.None, 8, StopBits.One); //115200
    41.  
    42.     public string message2;
    43.  
    44.     //Button States
    45.     bool button01State = false;
    46.  
    47.  
    48.  
    49.     void Awake () {
    50.         if (sending == null) {
    51.             DontDestroyOnLoad (gameObject);
    52.             sending = this;
    53.         } else if (sending != this) {
    54.             Destroy (gameObject);
    55.         }
    56. }
    57.  
    58.  
    59.     float timePassed = 0.0f;
    60.     // Use this for initialization
    61.     void Start () {
    62.         StartCoroutine(OpenConnection());
    63.         lightSlider = GetComponent<Slider> ();
    64.         if(slider == null) slider = GetComponent<Slider>(); // search slider in this object if its not set in unity inspector
    65.         if(source == null) source = GetComponent<AudioSource>(); // search audiosource in this object if its not set in unity inspector
    66.  
    67.         }
    68.    
    69.     // Update is called once per frame
    70.     void Update () {
    71.         /*string dataFromArduinoString = sp.ReadLine ();
    72.         int dFAI = int.Parse (dataFromArduinoString);
    73.         print (dFAI);
    74.         DirectionArrow (dFAI);*/
    75.  
    76.         try
    77.         {
    78.             //DirectionArrow(sp.ReadByte());
    79.             //print(sp.ReadByte());
    80.             string dataFromArduinoString = sp.ReadLine ();
    81.             int dFAI = int.Parse (dataFromArduinoString);
    82.             print (dFAI);
    83.             DirectionArrow (dFAI);
    84.         }
    85.         catch (System.Exception) {
    86.  
    87.         }
    88.             //print("BytesToRead" +sp.BytesToRead);
    89.             message2 = sp.ReadLine();
    90.            
    91.         string message = sp.ReadLine(); //get the message...
    92.         if(message == "") return; //if its empty stop right here
    93.         // parse the input to a float and normalize it (range 0..1) (we could do this already in the Arduino)
    94.  
    95.         float input =  1 -  float.Parse (message) / 100f;
    96.         // set the slider to the value
    97.         float oldValue = slider.value; // -------- this is new
    98.         slider.value = input;
    99.  
    100.         // after the slider is updated, we can check for the other things for example play sounds:
    101.  
    102.         if (source.isPlaying) return; // if we are playing a sound stop here
    103.  
    104.         // else check if we need to play a sound and do it
    105.         if (slider.value > 0.9f && oldValue <= 0.9f) // ---------this has changed
    106.             source.PlayOneShot (BrightnessAudioClips [Random.Range (0, BrightnessAudioClips.Length)]);
    107.  
    108.         else if (slider.value < 0.15f && oldValue >= 0.15f) //----------this has changed
    109.             source.PlayOneShot (DarknessAudioClips [Random.Range (0, DarknessAudioClips.Length)]);
    110.        
    111.  
    112.     }
    113.        
    114.  
    115.  
    116.     //public void OpenConnection() {
    117.     IEnumerator OpenConnection(){
    118.         yield return new WaitForSeconds(1.9f); // wait time
    119.        if (sp != null)
    120.        {
    121.          if (sp.IsOpen)
    122.          {
    123.           sp.Close();
    124.           print("Closing port, because it was already open!");
    125.          }
    126.          else
    127.          {
    128.           sp.Open();  // opens the connection
    129.           sp.ReadTimeout = 16;  // sets the timeout value before reporting error
    130.           print("Port Opened!");
    131.         //        message = "Port Opened!";
    132.          }
    133.        }
    134.        else
    135.        {
    136.          if (sp.IsOpen)
    137.          {
    138.           print("Port is already open");
    139.          }
    140.          else
    141.          {
    142.           print("Port == null");
    143.          }
    144.        }
    145.     }
    146.  
    147.     void OnApplicationQuit()
    148.     {
    149.        sp.Close();
    150.     }
    151.  
    152.     //Movie Player Toggle
    153.     public static void sendYellow(){
    154.         sp.Write("y");
    155.     }
    156.  
    157.     //Analyzer Toggle
    158.     public static void sendYellow2(){
    159.         sp.Write("A");
    160.     }
    161.  
    162.     //Pod 7DLA Toggle
    163.     public static void sendYellow3(){
    164.         sp.Write("D");
    165.     }
    166.  
    167.     //Pod PENG Toggle
    168.     public static void sendYellow4(){
    169.         sp.Write("P");
    170.     }
    171.  
    172.     //Pod 6RM Toggle
    173.     public static void sendYellow5(){
    174.         sp.Write("6");
    175.     }
    176.  
    177.     //Pod Laser Toggle
    178.     public static void sendYellow6(){
    179.         sp.Write("Z");
    180.     }
    181.  
    182.  
    183.     //Auto Phone Toggle
    184.     public static void sendGreen(){
    185.         sp.Write("g");
    186.         //sp.Write("\n");
    187.     }
    188.    
    189.     //Oil Slick Toggle
    190.     public static void sendRed(){
    191.         sp.Write("r");
    192.     }
    193.  
    194.     //Surveillance Mode Toggle
    195.     public static void sendBlue(){
    196.         sp.Write("b");
    197.     }
    198.    
    199.     //Scanner Toggle
    200.     public static void sendRed2(){
    201.         sp.Write("s");
    202.     }
    203.  
    204.     //Fog Lights Toggle
    205.     public static void sendGreen2(){
    206.         sp.Write("f");
    207.     }
    208.  
    209.     //Head Lights Toggle
    210.     public static void sendGreen3(){
    211.         sp.Write("h");
    212.     }
    213.  
    214.     //Hight Beams Toggle
    215.     public static void sendWhite(){
    216.         sp.Write("H");
    217.     }
    218.  
    219.     //Rear Hatch Popper
    220.     public static void sendPulse1(){
    221.         sp.Write("p");
    222.     }
    223.    
    224.     //Grappling Hook Launch
    225.     public static void sendPulse2(){
    226.         sp.Write("q");
    227.     }
    228.  
    229.     //Auto Doors Right Pulse
    230.     public static void sendPulse3(){
    231.         sp.Write("R");
    232.     }
    233.  
    234.     //Auto Doors Left Pulse
    235.     public static void sendPulse4(){
    236.         sp.Write("L");
    237.     }
    238.  
    239.     //Startup and Shutdown Pulse
    240.     public static void sendPulse5(){
    241.         sp.Write("S");
    242.     }
    243.        
    244.  
    245.     //System Guidance Close Button
    246.     public void  GoDTMFtone02(){
    247.         StartCoroutine(LoadT4());
    248.         GetComponent<AudioSource>().PlayOneShot(DTMFtone02);
    249.     }
    250.  
    251.     IEnumerator LoadT4(){
    252.         yield return new WaitForSeconds(0.0f); // wait time
    253.         CameraSwitcher cs1 = FindObjectOfType<CameraSwitcher>();
    254.         cs1.EnableCamera1();
    255.     }
    256.        
    257.     void DirectionArrow(int buttonStatus)
    258.     //void DirectionArrow(int Direction)
    259.     {
    260.        
    261.     switch (buttonStatus)
    262.     {
    263.         //OFF Buttons  States
    264.         case 0:
    265.             //deactivate Left Direction Arrow
    266.             SystemGuidanceManagerScript WAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    267.             WAOff.WestArrowOff ();
    268.  
    269.             SystemGuidanceManagerScript EAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    270.             EAOff.EastArrowOff();
    271.  
    272.             SystemGuidanceManagerScript SFXOff = FindObjectOfType<SystemGuidanceManagerScript>();
    273.             SFXOff.TopIndicatorOff();
    274.  
    275.             SystemGuidanceManagerScript BGSOff = FindObjectOfType<SystemGuidanceManagerScript>();
    276.             BGSOff.BarLEDsSounderOff();
    277.             break;
    278.         //LEFT BUTTON ON STATE
    279.         case 1:
    280.             //Activate Left Direction Arrow Indicator
    281.             SystemGuidanceManagerScript WAOn = FindObjectOfType<SystemGuidanceManagerScript>();
    282.             WAOn.WestArrow();
    283.  
    284.             SystemGuidanceManagerScript WBSOn = FindObjectOfType<SystemGuidanceManagerScript>();
    285.             WBSOn.BarLEDsSounderOn();
    286.             break;
    287.         //RIGHT BUTTON ON STATE
    288.         case 2:
    289.             //Activate Right Direction Arrow Indicator
    290.             SystemGuidanceManagerScript EAOn = FindObjectOfType<SystemGuidanceManagerScript> ();
    291.             EAOn.EastArrow ();
    292.  
    293.             SystemGuidanceManagerScript EBSOn = FindObjectOfType<SystemGuidanceManagerScript>();
    294.             EBSOn.BarLEDsSounderOn();
    295.             break;
    296.     }
    297.            
    298.     }
    299.  
    300. }
    301.  
     
  15. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Here is a video showing how the buttons are slow and sometimes unresponsive with the two codes in my last post.

     
  16. Polymorphik

    Polymorphik

    Joined:
    Jul 25, 2014
    Posts:
    599
    Try removing the delay in the arduino code
     
  17. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    I think the Delay is to "Debounce" the button. I reduced it to 20 but it still "Miss fires" ?
     
  18. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    OK Finally got that mess sorted out.
     
  19. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    What I had to do to get it working was do this in the Update:

    Code (CSharp):
    1. void Update () {
    2.         try
    3.         {
    4.             string message3 = sp.ReadLine(); //get the message...
    5.             if(message3 == "") return; //if its empty stop right here
    6.             print(message3);
    7.             DirectionArrow (message3.Trim());
    8.  
    9.         }
    10.         catch (System.Exception ex) {
    11.             print (ex.Message);
    12.             return;
    13.         }
    14.             //print("BytesToRead" +sp.BytesToRead);
    15.             message2 = sp.ReadLine();
    16.            
    17.         string message = sp.ReadLine(); //get the message...
    18.         if(message == "") return; //if its empty stop right here
    19.         // parse the input to a float and normalize it (range 0..1) (we could do this already in the Arduino)
    20.  
    21.         float input =  1 -  float.Parse (message) / 100f;
    22.         // set the slider to the value
    23.         float oldValue = slider.value; // -------- this is new
    24.         slider.value = input;
    25.  
    26.         // after the slider is updated, we can check for the other things for example play sounds:
    27.  
    28.         if (source.isPlaying) return; // if we are playing a sound stop here
    29.  
    30.         // else check if we need to play a sound and do it
    31.         if (slider.value > 0.9f && oldValue <= 0.9f) // ---------this has changed
    32.             source.PlayOneShot (BrightnessAudioClips [Random.Range (0, BrightnessAudioClips.Length)]);
    33.  
    34.         else if (slider.value < 0.15f && oldValue >= 0.15f) //----------this has changed
    35.             source.PlayOneShot (DarknessAudioClips [Random.Range (0, DarknessAudioClips.Length)]);
    36.        
    37.  
    38.     }

    And in the bottom part of the script where the switch statement is was to do this.

    Code (CSharp):
    1. void DirectionArrow(string buttonStatus)
    2.     {
    3.        
    4.         switch (buttonStatus)
    5.     {
    6.         //OFF Buttons  States
    7.         case "O":
    8.             //deactivate Left Direction Arrow
    9.             SystemGuidanceManagerScript WAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    10.             WAOff.WestArrowOff ();
    11.  
    12.             SystemGuidanceManagerScript EAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    13.             EAOff.EastArrowOff();
    14.  
    15.             SystemGuidanceManagerScript SFXOff = FindObjectOfType<SystemGuidanceManagerScript>();
    16.             SFXOff.TopIndicatorOff();
    17.  
    18.             SystemGuidanceManagerScript BGSOff = FindObjectOfType<SystemGuidanceManagerScript>();
    19.             BGSOff.BarLEDsSounderOff();
    20.  
    21.             MessageCentreManager2 MCM2DM = FindObjectOfType<MessageCentreManager2> ();
    22.             MCM2DM.GoDefaultMessage ();
    23.  
    24.             MessageCentreManager MCMDM = FindObjectOfType<MessageCentreManager> ();
    25.             MCMDM.GoKnightIndustriesMessage ();
    26.             break;
    27.         //LEFT BUTTON ON STATE
    28.         case "W":
    29.             //Activate Left Direction Arrow Indicator
    30.             SystemGuidanceManagerScript WAOn = FindObjectOfType<SystemGuidanceManagerScript> ();
    31.             WAOn.WestArrow ();
    32.  
    33.             SystemGuidanceManagerScript WBSOn = FindObjectOfType<SystemGuidanceManagerScript> ();
    34.             WBSOn.BarLEDsSounderOn ();
    35.  
    36.             MessageCentreManager2 MCM2LT = FindObjectOfType<MessageCentreManager2> ();
    37.             MCM2LT.GoLeftTurnMessage ();
    38.  
    39.             MessageCentreManager MCMLT = FindObjectOfType<MessageCentreManager> ();
    40.             MCMLT.GoLeftTurnMessage ();
    41.             break;
    42.         //RIGHT BUTTON ON STATE
    43.         case "E":
    44.             //Activate Right Direction Arrow Indicator
    45.             SystemGuidanceManagerScript EAOn = FindObjectOfType<SystemGuidanceManagerScript> ();
    46.             EAOn.EastArrow ();
    47.  
    48.             SystemGuidanceManagerScript EBSOn = FindObjectOfType<SystemGuidanceManagerScript>();
    49.             EBSOn.BarLEDsSounderOn();
    50.  
    51.             MessageCentreManager2 MCM2RT = FindObjectOfType<MessageCentreManager2> ();
    52.             MCM2RT.GoRightTurnMessage ();
    53.  
    54.             MessageCentreManager MCMRT = FindObjectOfType<MessageCentreManager> ();
    55.             MCMRT.GoRightTurnMessage ();
    56.             break;
    57.     }
    58.            
    59.     }
    60.  
    I did not have to change anything on the Arduino side although I did reduce the delay on the buttons from 50 to 20, I figure for a turn signal indicator switch that should be plenty as it's not a supper fast responsive type of switch like a game pad button ;)
     
  20. Polymorphik

    Polymorphik

    Joined:
    Jul 25, 2014
    Posts:
    599
    I actually ordered and Arduino Kit this got me interested in it.
     
    KnightRiderGuy likes this.
  21. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Right on Polymorphik,
    I think you are going to really enjoy it, I'm just barely scratching the surface with my project given some of the video I've seen on YouTube with what people have done with it and unity ;)
     
  22. Banshee119

    Banshee119

    Joined:
    Aug 27, 2017
    Posts:
    7
    This Interface is crazy, I love it
     
    KnightRiderGuy likes this.