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

How to Read in two Different Arduino Values

Discussion in 'Scripting' started by KnightRiderGuy, Jan 2, 2016.

  1. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    OK how else can I make this simpler. If the Arduino is sending out data like this to the Serial port.

    Screen Shot 2016-01-02 at 1.23.53 PM.png

    How can I use these two different data values in unity?
     
  2. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    OK it seems like I'm getting closer, according to the inspector it looks like the data from the Arduino is coming in as two separate entities.
    Screen Shot 2016-01-02 at 5.49.15 PM.png

    Still having a hard time trying to code this to read in the data properly in Unity though:

    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 TemperatureText;
    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 float TempSensorData;
    35.     public string TempSensorData;
    36.     public string LDRdata;
    37.     public string ButtonsData;
    38.  
    39.     public GameObject LightSlider;
    40.     public Slider slider;
    41.     Slider lightSlider;
    42.     public static Sending sending;
    43.  
    44.     //public static SerialPort sp = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
    45.     public static SerialPort sp = new SerialPort("/dev/cu.wchusbserial1420", 115200, Parity.None, 8, StopBits.One); //115200
    46.  
    47.  
    48.  
    49.     //Button States
    50.     bool button01State = false;
    51.  
    52.  
    53.     float timePassed = 0.0f;
    54.     // Use this for initialization
    55.     void Start () {
    56.         StartCoroutine(OpenConnection());
    57.         lightSlider = GetComponent<Slider> ();
    58.         if(slider == null) slider = GetComponent<Slider>(); // search slider in this object if its not set in unity inspector
    59.         if(source == null) source = GetComponent<AudioSource>(); // search audiosource in this object if its not set in unity inspector
    60.  
    61.         }
    62.  
    63.     // Update is called once per frame
    64.     void Update () {
    65.         try
    66.         {
    67.             /*ButtonsData = sp.ReadLine(); //get the message...
    68.             if(ButtonsData == "") return; //if its empty stop right here
    69.             print(ButtonsData);
    70.             DirectionArrow (ButtonsData.Trim());*/
    71.         //}
    72.  
    73.  
    74.  
    75.         TempSensorData = sp.ReadLine();
    76.         if (TempSensorData == "")
    77.             return;
    78.         TemperatureText.text = TempSensorData.ToString ();
    79.         }
    80.         catch (System.Exception ex) {
    81.             //print (ex.Message);
    82.             return;
    83.         }
    84.  
    85.  
    86.  
    87.             //print("BytesToRead" +sp.BytesToRead);
    88.         LDRdata = sp.ReadLine();
    89.          
    90.         //string message = sp.ReadLine(); //get the message...
    91.         if(LDRdata == "") return; //if its empty stop right here
    92.  
    93.         // parse the input to a float and normalize it (range 0..1) (we could do this already in the Arduino)
    94.         float input =  1 -  float.Parse (LDRdata) / 100f;
    95.         // set the slider to the value
    96.         float oldValue = slider.value;
    97.         slider.value = input;
    98.  
    99.         // after the slider is updated, we can check for the other things for example play sounds:
    100.         if (source.isPlaying) return; // if we are playing a sound stop here
    101.  
    102.         // else check if we need to play a sound and do it
    103.         if (slider.value > 0.9f && oldValue <= 0.9f) // ---------this has changed
    104.             source.PlayOneShot (BrightnessAudioClips [Random.Range (0, BrightnessAudioClips.Length)]);
    105.  
    106.         else if (slider.value < 0.15f && oldValue >= 0.15f) //----------this has changed
    107.             source.PlayOneShot (DarknessAudioClips [Random.Range (0, DarknessAudioClips.Length)]);
    108.      
    109.  
    110.     }
    111.      
    112.  
    113.  
    114.     //public void OpenConnection() {
    115.     IEnumerator OpenConnection(){
    116.         yield return new WaitForSeconds(1.9f); // wait time
    117.        if (sp != null)
    118.        {
    119.          if (sp.IsOpen)
    120.          {
    121.           sp.Close();
    122.           //print("Closing port, because it was already open!");
    123.          }
    124.          else
    125.          {
    126.           sp.Open();  // opens the connection
    127.           sp.ReadTimeout = 16;  // sets the timeout value before reporting error
    128.           //print("Port Opened!");
    129.         //        message = "Port Opened!";
    130.          }
    131.        }
    132.        else
    133.        {
    134.          if (sp.IsOpen)
    135.          {
    136.           //print("Port is already open");
    137.          }
    138.          else
    139.          {
    140.          // print("Port == null");
    141.          }
    142.        }
    143.     }
    144.  
    145.     void OnApplicationQuit()
    146.     {
    147.        sp.Close();
    148.     }
    149.  
    150.     //Movie Player Toggle
    151.     public static void sendYellow(){
    152.         sp.Write("y");
    153.     }
    154.  
    155.     //Analyzer Toggle
    156.     public static void sendYellow2(){
    157.         sp.Write("A");
    158.     }
    159.  
    160.     //Pod 7DLA Toggle
    161.     public static void sendYellow3(){
    162.         sp.Write("D");
    163.     }
    164.  
    165.     //Pod PENG Toggle
    166.     public static void sendYellow4(){
    167.         sp.Write("P");
    168.     }
    169.  
    170.     //Pod 6RM Toggle
    171.     public static void sendYellow5(){
    172.         sp.Write("6");
    173.     }
    174.  
    175.     //Pod Laser Toggle
    176.     public static void sendYellow6(){
    177.         sp.Write("Z");
    178.     }
    179.  
    180.  
    181.     //Auto Phone Toggle
    182.     public static void sendGreen(){
    183.         sp.Write("g");
    184.         //sp.Write("\n");
    185.     }
    186.  
    187.     //Oil Slick Toggle
    188.     public static void sendRed(){
    189.         sp.Write("r");
    190.     }
    191.  
    192.     //Surveillance Mode Toggle
    193.     public static void sendBlue(){
    194.         sp.Write("b");
    195.     }
    196.  
    197.     //Scanner Toggle
    198.     public static void sendRed2(){    //Need to Change to Arduino Port that does not flash on Start up
    199.         sp.Write("s");
    200.     }
    201.  
    202.     //Fog Lights Toggle
    203.     public static void sendGreen2(){
    204.         sp.Write("f");
    205.     }
    206.  
    207.     //Head Lights Toggle
    208.     public static void sendGreen3(){
    209.         sp.Write("h");
    210.     }
    211.  
    212.     //Hight Beams Toggle
    213.     public static void sendWhite(){
    214.         sp.Write("H");
    215.     }
    216.  
    217.     //Rear Hatch Popper
    218.     public static void sendPulse1(){
    219.         sp.Write("p");
    220.     }
    221.  
    222.     //Grappling Hook Launch
    223.     public static void sendPulse2(){
    224.         sp.Write("q");
    225.     }
    226.  
    227.     //Auto Doors Right Pulse
    228.     public static void sendPulse3(){
    229.         sp.Write("R");
    230.     }
    231.  
    232.     //Auto Doors Left Pulse
    233.     public static void sendPulse4(){
    234.         sp.Write("L");
    235.     }
    236.  
    237.     //Startup and Shutdown Pulse
    238.     public static void sendPulse5(){
    239.         sp.Write("Q");
    240.     }
    241.      
    242.  
    243.     //System Guidance Close Button
    244.     public void  GoDTMFtone02(){
    245.         StartCoroutine(LoadT4());
    246.         GetComponent<AudioSource>().PlayOneShot(DTMFtone02);
    247.     }
    248.  
    249.     IEnumerator LoadT4(){
    250.         yield return new WaitForSeconds(0.0f); // wait time
    251.         CameraSwitcher cs1 = FindObjectOfType<CameraSwitcher>();
    252.         cs1.EnableCamera1();
    253.     }
    254.      
    255.     void DirectionArrow(string buttonStatus)
    256.     {
    257.         switch (buttonStatus)
    258.     {
    259.         //OFF Buttons  States
    260.         case "O":
    261.             //deactivate Left Direction Arrow
    262.             SystemGuidanceManagerScript WAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    263.             WAOff.WestArrowOff ();
    264.  
    265.             SystemGuidanceManagerScript EAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    266.             EAOff.EastArrowOff();
    267.  
    268.             SystemGuidanceManagerScript NAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    269.             NAOff.NorthArrowOff();
    270.  
    271.             SystemGuidanceManagerScript SAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    272.             SAOff.SouthArrowOff();
    273.  
    274.             SystemGuidanceManagerScript SFXOff = FindObjectOfType<SystemGuidanceManagerScript>();
    275.             SFXOff.TopIndicatorOff();
    276.  
    277.             SystemGuidanceManagerScript BGSOff = FindObjectOfType<SystemGuidanceManagerScript>();
    278.             BGSOff.BarLEDsSounderOff();
    279.  
    280.             MessageCentreManager2 MCM2DM = FindObjectOfType<MessageCentreManager2> ();
    281.             MCM2DM.GoDefaultMessage ();
    282.  
    283.             MessageCentreManager MCMDM = FindObjectOfType<MessageCentreManager> ();
    284.             MCMDM.GoKnightIndustriesMessage ();
    285.             break;
    286.             //LEFT BUTTON ON STATE (COMPASS WEST)
    287.         case "W":
    288.             //Activate Left Direction Arrow Indicator
    289.             SystemGuidanceManagerScript WAOn = FindObjectOfType<SystemGuidanceManagerScript> ();
    290.             WAOn.WestArrow ();
    291.  
    292.             SystemGuidanceManagerScript WBSOn = FindObjectOfType<SystemGuidanceManagerScript> ();
    293.             WBSOn.BarLEDsSounderOn ();
    294.  
    295.             MessageCentreManager2 MCM2LT = FindObjectOfType<MessageCentreManager2> ();
    296.             MCM2LT.GoLeftTurnMessage ();
    297.  
    298.             MessageCentreManager MCMLT = FindObjectOfType<MessageCentreManager> ();
    299.             MCMLT.GoLeftTurnMessage ();
    300.             break;
    301.             //RIGHT BUTTON ON STATE (COMPASS EAST)
    302.         case "E":
    303.             //Activate Right Direction Arrow Indicator
    304.             SystemGuidanceManagerScript EAOn = FindObjectOfType<SystemGuidanceManagerScript> ();
    305.             EAOn.EastArrow ();
    306.  
    307.             SystemGuidanceManagerScript EBSOn = FindObjectOfType<SystemGuidanceManagerScript>();
    308.             EBSOn.BarLEDsSounderOn();
    309.  
    310.             MessageCentreManager2 MCM2RT = FindObjectOfType<MessageCentreManager2> ();
    311.             MCM2RT.GoRightTurnMessage ();
    312.  
    313.             MessageCentreManager MCMRT = FindObjectOfType<MessageCentreManager> ();
    314.             MCMRT.GoRightTurnMessage ();
    315.             break;
    316.             //FORWARD BUTTON ON STATE (COMPASS NORTH)
    317.         case "N":
    318.             //Activate Forward Direction Arrow Indicator (COMPASS NORTH)
    319.             SystemGuidanceManagerScript NAOn = FindObjectOfType<SystemGuidanceManagerScript> ();
    320.             NAOn.NorthArrow ();
    321.  
    322.             SystemGuidanceManagerScript NBSOn = FindObjectOfType<SystemGuidanceManagerScript>();
    323.             NBSOn.BarLEDsSounderOn();
    324.  
    325.             MessageCentreManager MCNH = FindObjectOfType<MessageCentreManager> ();
    326.             MCNH.GoNorthHeadingMessage ();
    327.  
    328.             MessageCentreManager2 MC2NH = FindObjectOfType<MessageCentreManager2> ();
    329.             MC2NH.GoCompasHeadNorthMessage ();
    330.             break;
    331.             //BACKWARD BUTTON ON STATE (COMPASS SOUTH)
    332.         case "S":
    333.             //Activate Backward Direction Arrow Indicator (COMPASS SOUTH)
    334.             SystemGuidanceManagerScript SAOn = FindObjectOfType<SystemGuidanceManagerScript> ();
    335.             SAOn.SouthArrow ();
    336.  
    337.             SystemGuidanceManagerScript SBSOn = FindObjectOfType<SystemGuidanceManagerScript>();
    338.             SBSOn.BarLEDsSounderOn();
    339.  
    340.             MessageCentreManager MCSH = FindObjectOfType<MessageCentreManager> ();
    341.             MCSH.GoSouthHeadingMessage ();
    342.  
    343.             MessageCentreManager2 MC2SH = FindObjectOfType<MessageCentreManager2> ();
    344.             MC2SH.GoCompasHeadSouthMessage ();
    345.             break;
    346.     }
    347.          
    348.     }
    349.  
    350. }
    351.  
     
  3. TheRaider

    TheRaider

    Joined:
    Dec 5, 2010
    Posts:
    2,245
    How does it know what com/serial port the arduino is connected too? Does it not need to know that?

    Note: I know this doesn't help you, I was just curious.
     
  4. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    The Arduino has a tool that tells you the serial port address it's connected too. in my case it's connected to SerialPort("/dev/cu.wchusbserial1420"

    I have no doubt when it gets moved to a PC and not my Mac that will change ;)

    I think on PC it's usually COM4
     
  5. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Someone in Unity Help suggested trying something like this but I'm clearly using it wrong.
    Hellllp.
    Code (CSharp):
    1. void Update()
    2.     {
    3.         var read = sp.ReadLine();
    4.         if (read == "")
    5.             return;
    6.  
    7.         MessageReceived(read);
    8.     }
    9.  
    10.     void MessageReceived(string message)
    11.     {
    12.         var type = message[0];
    13.         var value = float.Parse(message.Substring(1));
    14.         switch (type)
    15.         {
    16.         case 'T':
    17.             //HandleTemp(value);
    18.             TempSensorData = sp.ReadLine();
    19.             if (TempSensorData == "")
    20.                 return;
    21.             TemperatureText.text = TempSensorData.ToString ();
    22.             break;
    23.         case 'L':
    24.             //HandleLight(value);
    25.             break;
    26.         default:
    27.             print("Invalid");
    28.             break;
    29.         }
    30.     }
    At the top of my C# script I have the following variable defined which I don't think are being used correctly:

    Code (CSharp):
    1.  
    2.     public string TempSensorData;
    3.     public string LDRdata;
    4.     public string ButtonsData;
     
  6. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Ok with some awesome help from ShapeShifter from the Arduino forums I was able to get this working.
    This is what I had to do.

    Code (CSharp):
    1. void Update()
    2.     {
    3.         string read = sp.ReadLine();
    4.         if (read == "")
    5.             return;
    6.  
    7.         MessageReceived(read);
    8.     }
    9.  
    10.     void MessageReceived(string message)
    11.     {
    12.         char type = message[0];
    13.         string value = message.Substring(1);
    14.  
    15.         switch (type)
    16.         {
    17.         case 'T':
    18.             //temperature sensor reading
    19.             //TemperatureText = value;
    20.             //TempSensorData = value;
    21.             //TemperatureText.text = TempSensorData.ToString ();
    22.             TemperatureText.text = value;
    23.             break;
    24.  
    25.         case 'L':
    26.             //light sensor reading
    27.             LDRdata = value;
    28.             if(LDRdata == "") return; //if its empty stop right here
    29.  
    30.             // parse the input to a float and normalize it (range 0..1) (we could do this already in the Arduino)
    31.             float input =  1 -  float.Parse (LDRdata) / 100f;
    32.             // set the slider to the value
    33.             float oldValue = slider.value;
    34.             slider.value = input;
    35.  
    36.             // after the slider is updated, we can check for the other things for example play sounds:
    37.             if (source.isPlaying) return; // if we are playing a sound stop here
    38.  
    39.             // else check if we need to play a sound and do it
    40.             if (slider.value > 0.9f && oldValue <= 0.9f) // ---------this has changed
    41.                 source.PlayOneShot (BrightnessAudioClips [Random.Range (0, BrightnessAudioClips.Length)]);
    42.  
    43.             else if (slider.value < 0.15f && oldValue >= 0.15f) //----------this has changed
    44.                 source.PlayOneShot (DarknessAudioClips [Random.Range (0, DarknessAudioClips.Length)]);
    45.             break;
    46.  
    47.         case 'O':
    48.             //deactivate Left Direction Arrow
    49.             // your existing code from your DirectionArrow() function goes here...
    50.             //deactivate Left Direction Arrow
    51.             SystemGuidanceManagerScript WAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    52.             WAOff.WestArrowOff ();
    53.  
    54.             SystemGuidanceManagerScript EAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    55.             EAOff.EastArrowOff();
    56.  
    57.             SystemGuidanceManagerScript NAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    58.             NAOff.NorthArrowOff();
    59.  
    60.             SystemGuidanceManagerScript SAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    61.             SAOff.SouthArrowOff();
    62.  
    63.             SystemGuidanceManagerScript SFXOff = FindObjectOfType<SystemGuidanceManagerScript>();
    64.             SFXOff.TopIndicatorOff();
    65.  
    66.             SystemGuidanceManagerScript BGSOff = FindObjectOfType<SystemGuidanceManagerScript>();
    67.             BGSOff.BarLEDsSounderOff();
    68.  
    69.             MessageCentreManager2 MCM2DM = FindObjectOfType<MessageCentreManager2> ();
    70.             MCM2DM.GoDefaultMessage ();
    71.  
    72.             MessageCentreManager MCMDM = FindObjectOfType<MessageCentreManager> ();
    73.             MCMDM.GoKnightIndustriesMessage ();
    74.             break;
    I didn't include all of the button input switch statements as they are pretty straight forward and copy & paste from my original buttons switch statement.

    here is a video demo of the scenario working.