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

Switch Statement Do Something When Sensor Value Changes

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

  1. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Ok I have this temperature sensor hooked up to an Arduino connected to Unity through the serial port sending in data for the temperature read out I have set up as a Ui text. What would be the best way fro me to trigger audio clips in a set up like this:

    Code (CSharp):
    1. char type = message[0];
    2.         string value = message.Substring(1);
    3.  
    4.         switch (type)
    5.         {
    6.         case 'T':
    7.             //temperature sensor reading
    8.             TemperatureText.text = TempSensorData.ToString ();
    9.             TempSensorData = value;
    10.             //Do Something If Temperature Falls Below 0 Degrees C
    11.  
    12.  
    13.             //Do Something If Temperature Rises Above 90 Degrees C
    14.             break;
     
  2. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    I would use the switch statement only to build a class which can encapsulate the behavior.

    Code (csharp):
    1. // -- in your arduino reading code --
    2. char type = message[0];
    3. IArduinoSensorBehavior behavior = null;
    4.  
    5. switch (type)
    6. {
    7. case 'T':
    8.   behavior = new (TemperatureBehavior(message.Substring(1));
    9. break;
    10. default:
    11.   throw new NotImplementedException(new String(type));
    12. }
    13.  
    14. behavior.Act();
    15.  
    16. // -- in another file(s) --
    17.  
    18. public interface IArduinoSensorBehaviour
    19. {
    20.   public void Act();
    21. }
    22.  
    23. public class TemperatureBehaviour : IArduinoSensorBehaviour
    24. {
    25.  
    26.   private readonly float temperature;
    27.   public TemperatureBehaviour(string temperatureReading)
    28.   {
    29.     this.temperature = float.Parse(temperatureReading);
    30.   }
    31.   public void Act()
    32.   {
    33.     if (temperature < 0)
    34.       Console.Write("\a");
    35.   }
    36. }
    You could do something similar using function calls instead of an interface and so many classes if your logic is going to remain this simple
     
  3. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Thanks eisenpony this looks interesting. now would this allow my existing UI text to still read out the current temperature onto the screen on my Ui canvas?
    I'm guessing I would make another script fro that bottom part that would read if my temperature fell below "0" correct?
     
  4. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    One option is to pass the UI Canvas to the TemperatureBehaviour class and have it take care of writing at the same time it plays an audio clip.

    Code (csharp):
    1. public class TemperatureBehaviour : IArduinoSensorBehaviour
    2. {
    3.  
    4.   private readonly float temperature;
    5.   private readonly Canvas canvas;
    6.   public TemperatureBehaviour(string temperatureReading, Canvas canvas)
    7.   {
    8.     this.temperature = float.Parse(temperatureReading);
    9.     this.canvas = canvas;
    10.   }
    11.   public void Act()
    12.   {
    13.     if (temperature < 0)
    14.     {
    15.       Console.Write("\a");
    16.       // code to print to canvas
    17.     }
    18.   }
    19. }
     
  5. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Just wondering why I would pass the UI canvas and not just deal with the UI text that is a child of a panel on the canvas? Seems a little confusing to me?
     
  6. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    Sure, that sounds great. No need to pass more than needed..
     
  7. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Thanks eisenpony

    I was playing around with something like this but I'm not sure if that will work. I defined a float at the top of my script like this just to set some sort of temperature threshold.

    Code (CSharp):
    1. float coldLimitTemperature = 10.0f;
    Code (CSharp):
    1. void MessageReceived(string message)
    2.     {
    3.         char type = message[0];
    4.         string value = message.Substring(1);
    5.  
    6.         switch (type)
    7.         {
    8.         case 'T':
    9.             //temperature sensor reading
    10.             TemperatureText.text = TempSensorData.ToString ();
    11.             TempSensorData = value;
    12.             //Do Something If Temperature Falls Below 0 Degrees C
    13.             // parse the input to a float and normalize it (range 0..1) (we could do this already in the Arduino)
    14.             float TempInput = 1 - float.Parse (TempSensorData) / 100f;
    15.             if (coldLimitTemperature < 15.0f) {
    16.                 print ("It's Chilly In Here");
    17.             }
    18.             //Do Something If Temperature Rises Above 90 Degrees C
    19.             break;
    20.  
    21.         case 'L':
    22.             //light sensor reading
    23.             LDRdata = value;
    24.             if(LDRdata == "") return; //if its empty stop right here
    25.  
    26.             // parse the input to a float and normalize it (range 0..1) (we could do this already in the Arduino)
    27.             float input =  1 -  float.Parse (LDRdata) / 100f;
    28.             // set the slider to the value
    29.             float oldValue = slider.value;
    30.             slider.value = input;
    31.  
    32.             // after the slider is updated, we can check for the other things for example play sounds:
    33.             if (source.isPlaying) return; // if we are playing a sound stop here
    34.  
    35.  
    36.             // else check if we need to play a sound and do it
    37.             if //(slider.value > 0.9f && oldValue <= 0.9f) //This will call the voice no matter what time of day or night it is
    38.                 (slider.value > 0.9f && oldValue <= 0.9f && (sysHour >= 18 || sysHour <= 6)) //Voice Will Only Activate between 6PM & 6AM
    39.                 StartCoroutine(BrightnessResponse());
    40.  
    41.             else if (slider.value < 0.10f && oldValue >= 0.10f) //At These Values activate a "Darkness Detected" response
    42.                 StartCoroutine(DarknessResponse());
    43.             break;
     
    Last edited: Jan 10, 2016
  8. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Damn!! I thought I was closer with it today but I keep getting error messages. I thought it would be similar to how the Light sensor is parsed but I guess not?
     
  9. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    What is your error? Sorry, I'm not familiar with the readings passed back by the Arduino.

    Your code looks a bit off in this spot
    Code (CSharp):
    1.         case 'T':
    2.             //temperature sensor reading
    3.             TemperatureText.text = TempSensorData.ToString ();
    I don't see where you initialize TempSenosrData before this line, so calling ToString() will give a NullReferenceException.

    Also here
    Code (CSharp):
    1.             if (coldLimitTemperature < 15.0f) {
    2.                 print ("It's Chilly In Here");
    3.             }
    Why check coldLimitTemperateure against the literal 15.0f? This will always be true unless you set coldLimitTemperature somewhere else

    Did you mean to compare coldLimitTemperature with the value returned by the Arduino?
     
    KnightRiderGuy likes this.
  10. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Yes, the temperature data is reading in fine and updates the UI text element perfectly, I was trying to see if I could set a threshold at the top of the script like this
    Code (CSharp):
    1. float coldLimitTemperature = 10.0f;
    And then somehow use some if statements to trigger audio events if the temperature was below or above certain set values.
    Hopefully that made sense?
     
  11. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    I'm not sure it's really all that important as everything is basically working fine there are no problems with receiving the data from the Arduino. All I'm looking to do id do something with the temperature values in pretty much the same way I use the LDR or light sensor values.

    But here is the Arduino code part for both the LDR and Temperature sensor... but like I say all of that is working perfectly as it should. Even in Unity I'm reading out my temperature sensor data onto UI text that I display on the screen perfectly.... just want to dod a little more with the data is all ;)

    Code (CSharp):
    1. void loop()
    2. {
    3.   //Request temperature from DS18B20
    4.   sensor_incar.requestTemperatures();
    5.   //Get the temperature
    6.   float incarTemperature = sensor_incar.getTempCByIndex(0);
    7.  
    8.   //Send it to Unity
    9.   Serial.print("T");
    10.   Serial.println(incarTemperature);
    11.   //Serial.println("T32.00:"); //Not sure how this Works as some sort of marker?
    12.  
    13.   // read the new light value (in range 0..1023):
    14.      int sensorValue = analogRead(lightSensorPin);
    15.      // if the value changed by 10
    16.      if(lightSensorValue - sensorValue > 10 || sensorValue - lightSensorValue > 10){
    17.          lightSensorValue = sensorValue; // save the new value
    18.          float p = lightSensorValue * (100.0 / 1023.0);    // make the value to range 0..100
    19.          Serial.print("L");
    20.          Serial.println(p); // send it to unity
    21.        
    22.      }
    23.   //delay(30);
    Screen Shot 2016-01-03 at 4.49.36 PM.png
     
  12. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    Sorry zentaiguy, I'm starting to realize I misinterpreted the original question. Correct me if I'm wrong but basically: are you are having trouble getting Unity to play a sound under certain circumstances?

    So, setting thresholds at the top of the script seems like a reasonable approach but you will need to solve your current error first. You said you were receiving an error, I assumed that meant in Unity. What error are you getting?

    I'm still a little gray on exactly the trouble you are having but maybe this will help.

    This bit of code looks like it is in the wrong order to me:
    Code (CSharp):
    1. case 'T':
    2.   //temperature sensor reading
    3.   TemperatureText.text = TempSensorData.ToString ();
    4.   TempSensorData = value;
    It looks like you are calling ToString on an object which has not been initialized, so that will cause a NullReferenceException.

    As for the logic for playing a sound after crossing a threshold, I think you will need to retain the last known temperature in order to see if the threshold was crossed on this iteration or some previous iteration. You presumably only want to play the sound once..

    something like
    Code (CSharp):
    1. float coldLimitTemperature = 10.0f;
    2. float lastTempSensorData = 0f;
    Code (CSharp):
    1.         case 'T':
    2.             //temperature sensor reading
    3.             TempSensorData = value;
    4.             TemperatureText.text = TempSensorData.ToString();
    5.  
    6.             if (TempSensorData < coldLimitTemperature && lastTempSensorData > coldLimitTemperature) {
    7.                 // play the audio source
    8.             }
    9.             break;
    10.  
    Note this logic doesn't handle the case when the sensor's first report is below the threshold. It also doesn't support additional thresholds.. you would need a new variable and if statement for each.
     
    KnightRiderGuy likes this.
  13. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Hmmm I thought you might have been on to something there I modified based on what you had here like this.

    Code (CSharp):
    1. float coldLimitTemperature = 10.0f;
    2.     float lastTempSensorData = 0f;
    Code (CSharp):
    1. void MessageReceived(string message)
    2.     {
    3.         char type = message[0];
    4.         string value = message.Substring(1);
    5.  
    6.         switch (type)
    7.         {
    8.         case 'T':
    9.             //temperature sensor reading
    10.             TemperatureText.text = TempSensorData.ToString ();
    11.             TempSensorData = value;
    12.             //Do Something If Temperature Falls Below 0 Degrees C
    13.             if (TempSensorData < coldLimitTemperature && lastTempSensorData > coldLimitTemperature) {
    14.                 // play the audio source
    15.                 print ("It's Chilly In Here");
    16.             }
    17.          
    18.             //Do Something If Temperature Rises Above 90 Degrees C
    19.  
    20.             break;
    21.  
    It looked goo to me logically but I get this error message:

    Code (CSharp):
    1. Assets/Scripts/Sending.cs(113,29): error CS0019: Operator `<' cannot be applied to operands of type `string' and `float'
    Just so you can see how it's being applied here is a video demo.

     
  14. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    Whoops. That's what the float.parse is supposed to do in my previous code.

     
    KnightRiderGuy likes this.
  15. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Thanks eisenpony

    Maybe it might help to see the whole code :)

    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; //System Hour
    12.     int sysDay = System.DateTime.Now.Day; //System Day
    13.     int sysMonth = System.DateTime.Now.Month; //System Month
    14.  
    15.     public AudioSource source;
    16.  
    17.     //UI Text Reference
    18.     public Text TemperatureText;
    19.  
    20.     //_isPlayingSound is true when a sound is currently playing - just as the name suggests.
    21.     //private bool _isPlayingSound;
    22.  
    23.     const float sliderChangeVelocity = 0.5f;
    24.     private float desiredSliderValue;
    25.  
    26.     //public float TempSensorData;
    27.     public string TempSensorData;
    28.     public string LDRdata;
    29.     public string ButtonsData;
    30.  
    31.     float coldLimitTemperature = 10.0f;
    32.     float lastTempSensorData = 0f;
    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.  
    43.  
    44.     //Button States
    45.     bool button01State = false;
    46.  
    47.     float timePassed = 0.0f;
    48.  
    49.  
    50.     /*void Awake () {
    51.         if (sending == null) {
    52.             DontDestroyOnLoad (gameObject);
    53.             sending = this;
    54.         } else if (sending != this) {
    55.             Destroy (gameObject);
    56.         }
    57.     }*/
    58.  
    59.     void Awake () {
    60.         if (sending == null) {
    61.             DontDestroyOnLoad (gameObject);
    62.             sending = this;
    63.         } else if (sending != this) {
    64.             if (this.lightSlider != null && sending.lightSlider == null) {
    65.                 Destroy (sending.gameObject);
    66.                 sending = this;
    67.             } else {
    68.                 Destroy(this);
    69.             }
    70.         }
    71.     }
    72.  
    73.     // Use this for initialization
    74.     void Start () {
    75.         StartCoroutine(OpenConnection());
    76.         lightSlider = GetComponent<Slider> ();
    77.         if(slider == null) slider = GetComponent<Slider>(); // search slider in this object if its not set in unity inspector
    78.         //if(source == null) source = GetComponent<AudioSource>(); // search audiosource in this object if its not set in unity inspector
    79.  
    80.         }
    81.  
    82.     void Update()
    83.     {
    84.         try{
    85.         string read = sp.ReadLine();
    86.         if (read == "")
    87.             return;
    88.        
    89.        
    90.         MessageReceived(read);
    91.         }
    92.             catch{
    93.             }
    94.         //Birthday greeting Check - Michaels
    95.         if (System.DateTime.Now.Month == 08 && System.DateTime.Now.Day == 25) {
    96.             //Start Birday Message Request
    97.             StartCoroutine (BirthdayMessageRequest ());
    98.         }
    99.     }
    100.  
    101.     void MessageReceived(string message)
    102.     {
    103.         char type = message[0];
    104.         string value = message.Substring(1);
    105.  
    106.         switch (type)
    107.         {
    108.         case 'T':
    109.             //temperature sensor reading
    110.             TempSensorData = value;
    111.             //TempSensorData = float.Parse(value);
    112.             TemperatureText.text = TempSensorData.ToString ();
    113.  
    114.             //Do Something If Temperature Falls Below 0 Degrees C
    115.             /*if (TempSensorData < coldLimitTemperature && lastTempSensorData > coldLimitTemperature) {
    116.                 // play the audio source
    117.                 print ("It's Chilly In Here");
    118.             }
    119.             lastTempSensorData = TempSensorData;*/
    120.             //Do Something If Temperature Rises Above 90 Degrees C
    121.  
    122.             break;
    123.  
    124.         case 'L':
    125.             //light sensor reading
    126.             LDRdata = value;
    127.             if (LDRdata == "")
    128.                 return; //if its empty stop right here
    129.  
    130.             // parse the input to a float and normalize it (range 0..1) (we could do this already in the Arduino)
    131.             float input = 1 - float.Parse (LDRdata) / 100f;
    132.             // set the slider to the value
    133.             float oldValue = slider.value;
    134.             slider.value = input;
    135.  
    136.             // after the slider is updated, we can check for the other things for example play sounds:
    137.             if (source.isPlaying)
    138.                 return; // if we are playing a sound stop here
    139.  
    140.  
    141.             // else check if we need to play a sound and do it
    142.             if (slider.value > 0.9f && oldValue <= 0.9f && (sysHour >= 17 || sysHour <= 6)) //Voice Will Only Activate between 6PM & 6AM
    143.                 StartCoroutine(BrightnessResponse());
    144.  
    145.             else if (slider.value < 0.10f && oldValue >= 0.10f && (sysHour >= 6 || sysHour <= 17)) //Voice Will Only Activate between 6AM & 6PM
    146.                 StartCoroutine(DarknessResponseOP2());
    147.  
    148.             break;
    149.  
    150.         case 'O':
    151.             //deactivate Left Direction Arrow
    152.             SystemGuidanceManagerScript WAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    153.             WAOff.WestArrowOff ();
    154.  
    155.             SystemGuidanceManagerScript EAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    156.             EAOff.EastArrowOff();
    157.  
    158.             SystemGuidanceManagerScript NAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    159.             NAOff.NorthArrowOff();
    160.  
    161.             SystemGuidanceManagerScript SAOff = FindObjectOfType<SystemGuidanceManagerScript>();
    162.             SAOff.SouthArrowOff();
    163.  
    164.             SystemGuidanceManagerScript SFXOff = FindObjectOfType<SystemGuidanceManagerScript>();
    165.             SFXOff.TopIndicatorOff();
    166.  
    167.             SystemGuidanceManagerScript BGSOff = FindObjectOfType<SystemGuidanceManagerScript>();
    168.             BGSOff.BarLEDsSounderOff();
    169.  
    170.             MessageCentreManager2 MCM2DM = FindObjectOfType<MessageCentreManager2> ();
    171.             MCM2DM.GoDefaultMessage ();
    172.  
    173.             MessageCentreManager MCMDM = FindObjectOfType<MessageCentreManager> ();
    174.             MCMDM.GoKnightIndustriesMessage ();
    175.             break;
    176.  
    177.         case 'W':
    178.             //Activate Left Direction Arrow Indicator
    179.             SystemGuidanceManagerScript WAOn = FindObjectOfType<SystemGuidanceManagerScript> ();
    180.             WAOn.WestArrow ();
    181.  
    182.             SystemGuidanceManagerScript WBSOn = FindObjectOfType<SystemGuidanceManagerScript> ();
    183.             WBSOn.BarLEDsSounderOn ();
    184.  
    185.             MessageCentreManager2 MCM2LT = FindObjectOfType<MessageCentreManager2> ();
    186.             MCM2LT.GoLeftTurnMessage ();
    187.  
    188.             MessageCentreManager MCMLT = FindObjectOfType<MessageCentreManager> ();
    189.             MCMLT.GoLeftTurnMessage ();
    190.             break;
    191.  
    192.         case 'E':
    193.             //Activate Right Direction Arrow Indicator
    194.             SystemGuidanceManagerScript EAOn = FindObjectOfType<SystemGuidanceManagerScript> ();
    195.             EAOn.EastArrow ();
    196.  
    197.             SystemGuidanceManagerScript EBSOn = FindObjectOfType<SystemGuidanceManagerScript>();
    198.             EBSOn.BarLEDsSounderOn();
    199.  
    200.             MessageCentreManager2 MCM2RT = FindObjectOfType<MessageCentreManager2> ();
    201.             MCM2RT.GoRightTurnMessage ();
    202.  
    203.             MessageCentreManager MCMRT = FindObjectOfType<MessageCentreManager> ();
    204.             MCMRT.GoRightTurnMessage ();
    205.             break;
    206.  
    207.         case 'N':
    208.             //Activate Forward Direction Arrow Indicator (COMPASS NORTH)
    209.             SystemGuidanceManagerScript NAOn = FindObjectOfType<SystemGuidanceManagerScript> ();
    210.             NAOn.NorthArrow ();
    211.  
    212.             SystemGuidanceManagerScript NBSOn = FindObjectOfType<SystemGuidanceManagerScript>();
    213.             NBSOn.BarLEDsSounderOn();
    214.  
    215.             MessageCentreManager MCNH = FindObjectOfType<MessageCentreManager> ();
    216.             MCNH.GoNorthHeadingMessage ();
    217.  
    218.             MessageCentreManager2 MC2NH = FindObjectOfType<MessageCentreManager2> ();
    219.             MC2NH.GoCompasHeadNorthMessage ();
    220.             break;
    221.  
    222.         case 'S':
    223.             //Activate Backward Direction Arrow Indicator (COMPASS SOUTH)
    224.             SystemGuidanceManagerScript SAOn = FindObjectOfType<SystemGuidanceManagerScript> ();
    225.             SAOn.SouthArrow ();
    226.  
    227.             SystemGuidanceManagerScript SBSOn = FindObjectOfType<SystemGuidanceManagerScript>();
    228.             SBSOn.BarLEDsSounderOn();
    229.  
    230.             MessageCentreManager MCSH = FindObjectOfType<MessageCentreManager> ();
    231.             MCSH.GoSouthHeadingMessage ();
    232.  
    233.             MessageCentreManager2 MC2SH = FindObjectOfType<MessageCentreManager2> ();
    234.             MC2SH.GoCompasHeadSouthMessage ();
    235.             break;
    236.  
    237.         default:
    238.             // An unexpexted type of data was received
    239.             print("Invalid");
    240.             break;
    241.         }
    242.     }
    243.        
    244.  
    245.     //public void OpenConnection() {
    246.     IEnumerator OpenConnection(){
    247.         yield return new WaitForSeconds(1.9f); // wait time
    248.        if (sp != null)
    249.        {
    250.          if (sp.IsOpen)
    251.          {
    252.           sp.Close();
    253.           //print("Closing port, because it was already open!");
    254.          }
    255.          else
    256.          {
    257.           sp.Open();  // opens the connection
    258.           sp.ReadTimeout = 16;  // sets the timeout value before reporting error
    259.           print("Port Opened!");
    260.                 //message = "Port Opened!";
    261.          }
    262.        }
    263.        else
    264.        {
    265.          if (sp.IsOpen)
    266.          {
    267.           print("Port is already open");
    268.          }
    269.          else
    270.          {
    271.           print("Port == null");
    272.          }
    273.        }
    274.     }
    275.  
    276.     void OnApplicationQuit()
    277.     {
    278.        sp.Close();
    279.     }
    280.  
    281.     //Movie Player Toggle
    282.     public static void sendYellow(){
    283.         sp.Write("y");
    284.     }
    285.  
    286.     //Analyzer Toggle
    287.     public static void sendYellow2(){
    288.         sp.Write("A");
    289.     }
    290.  
    291.     //Pod 7DLA Toggle
    292.     public static void sendYellow3(){
    293.         sp.Write("D");
    294.     }
    295.  
    296.     //Pod PENG Toggle
    297.     public static void sendYellow4(){
    298.         sp.Write("P");
    299.     }
    300.  
    301.     //Pod 6RM Toggle
    302.     public static void sendYellow5(){
    303.         sp.Write("6");
    304.     }
    305.  
    306.     //Pod Laser Toggle
    307.     public static void sendYellow6(){
    308.         sp.Write("Z");
    309.     }
    310.  
    311.  
    312.     //Auto Phone Toggle
    313.     public static void sendGreen(){
    314.         sp.Write("g");
    315.         //sp.Write("\n");
    316.     }
    317.    
    318.     //Oil Slick Toggle
    319.     public static void sendRed(){
    320.         sp.Write("r");
    321.     }
    322.  
    323.     //Surveillance Mode Toggle
    324.     public static void sendBlue(){
    325.         sp.Write("b");
    326.     }
    327.    
    328.     //Scanner Toggle
    329.     public static void sendRed2(){    //Need to Change to Arduino Port that does not flash on Start up
    330.         sp.Write("s");
    331.     }
    332.  
    333.     //Fog Lights Toggle
    334.     public static void sendGreen2(){
    335.         sp.Write("f");
    336.     }
    337.  
    338.     //Head Lights Toggle
    339.     public static void sendGreen3(){
    340.         sp.Write("h");
    341.     }
    342.  
    343.     //Hight Beams Toggle
    344.     public static void sendWhite(){
    345.         sp.Write("H");
    346.     }
    347.  
    348.     //Rear Hatch Popper
    349.     public static void sendPulse1(){
    350.         sp.Write("p");
    351.     }
    352.    
    353.     //Grappling Hook Launch
    354.     public static void sendPulse2(){
    355.         sp.Write("q");
    356.     }
    357.  
    358.     //Auto Doors Right Pulse
    359.     public static void sendPulse3(){
    360.         sp.Write("R");
    361.     }
    362.  
    363.     //Auto Doors Left Pulse
    364.     public static void sendPulse4(){
    365.         sp.Write("L");
    366.     }
    367.  
    368.     //Startup and Shutdown Pulse
    369.     public static void sendPulse5(){
    370.         sp.Write("Q");
    371.     }
    372.  
    373.     //Send Birthday Request To Message Centre - Michael's Birthday
    374.     IEnumerator BirthdayMessageRequest(){
    375.         yield return new WaitForSeconds(3.5f); // wait time
    376.         MessageCentreManager BM = FindObjectOfType<MessageCentreManager>();
    377.         BM.GoBirthdayMessage ();
    378.     }
    379.        
    380.  
    381.     //Send Brightness Detected Audio Resoponse Request to Voice Box Object
    382.     IEnumerator BrightnessResponse(){
    383.         yield return new WaitForSeconds(0.5f); // wait time
    384.         VoiceBox VBbr = FindObjectOfType<VoiceBox>();
    385.         VBbr.BrightnessDetected ();
    386.  
    387.         MessageCentreManager MCMbd = FindObjectOfType<MessageCentreManager>();
    388.         MCMbd.GoBrightnessDetectedMessage ();
    389.         print ("Brilliant Light Detected Michael");
    390.     }
    391.  
    392.     //Send Darkness Detected Audio Resoponse Request to Voice Box Object
    393.     IEnumerator DarknessResponse(){
    394.         yield return new WaitForSeconds(0.5f); // wait time
    395.         VoiceBox VBdr = FindObjectOfType<VoiceBox>();
    396.         VBdr.DarknessDetected ();
    397.         //Send Message for Message Centre to display "AMB LGHT INSUF" message
    398.         MessageCentreManager MCMdd = FindObjectOfType<MessageCentreManager>();
    399.         MCMdd.GoDarknessDetectedMessage ();
    400.  
    401.     }
    402.  
    403.     //Send Darkness Detected Audio Response Request to the Voice Box for Suspected Un-Naturally Occuring Darkness
    404.     IEnumerator DarknessResponseOP2(){
    405.         yield return new WaitForSeconds(0.5f); // wait time
    406.         VoiceBox VBudd = FindObjectOfType<VoiceBox>();
    407.         VBudd.UnNaturalDarknessDetected ();
    408.         print ("Darkness Must Not Be Naturally Occuring Michael");
    409.     }
    410.  
    411. }
    412.  
     
  16. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Thanks

    I did post my entire code page in my last post. With the new code like this:
    Code (CSharp):
    1. case 'T':
    2.             //temperature sensor reading
    3.             //TempSensorData = value;
    4.             TempSensorData = float.Parse(value);
    5.             TemperatureText.text = TempSensorData.ToString ();
    6.  
    7.             //Do Something If Temperature Falls Below 0 Degrees C
    8.             if (TempSensorData < coldLimitTemperature && lastTempSensorData > coldLimitTemperature) {
    9.                 // play the audio source
    10.                 print ("It's Chilly In Here");
    11.             }
    12.             lastTempSensorData = TempSensorData;
    13.             //Do Something If Temperature Rises Above 90 Degrees C
    14.  
    15.             break;
    I get the following errors:
    Code (CSharp):
    1. Assets/Scripts/Sending.cs(111,25): error CS0029: Cannot implicitly convert type `float' to `string'
    2.  
    and

    Code (CSharp):
    1. Assets/Scripts/Sending.cs(115,29): error CS0019: Operator `<' cannot be applied to operands of type `string' and `float'
    and

    Code (CSharp):
    1. Assets/Scripts/Sending.cs(119,25): error CS0029: Cannot implicitly convert type `string' to `float'
    2.  
     
  17. Spellbook

    Spellbook

    Joined:
    May 21, 2015
    Posts:
    29
    Your variable TempSensorData is defined as a string, and will always be a string even if you set it to a float. It implicitly converts it back to a string.

    You'll need to create local float variable to hold the parsed information as a float:

    TempSensorData =value;
    float currentData = float.Parse(value);

    if(currentData < coldLimitTemperature && lastTempSensorData > coldLimitTemperature)
    {
    //do something
    }
    lastTempSensorData = currentData;


    You might want to consider changing TempSensorData and any other "this is always number" variables into floats or ints, unless there's a really good reason to keep them as strings. Otherwise it's just making things more complex for you, and creates more opportunity for bugs.
     
    Last edited: Jan 12, 2016
  18. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Thanks Spellbook
    I think I need it as a string in order to change the UI text if I understand that part of it correctly?
    Code is not really my strong point so I'm not sure.

    Late Edit:
    I just tried out you new code, it removed the errors but my UI text no longer displays the temperature?
     
    Last edited: Jan 12, 2016
  19. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    I currently need the information as a string for the UI text to render. That part is working fine. I keep having issues trying to get the data to work with a couple of if statements to check what the value is so that if the temperature value is at a cold value then execute something to happen and same thing if the temperature is at a hot value to execute something.
    Not sure if you got my last post in response to your about it clearing up the error but disabled my UI text from rendering out the temperature value onto the canvas. ?
     
  20. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    Sorry zentaiguy -- I've been really busy the last few days.

    Okay, you need it as a string to render to the canvas. Well, you actually have both in code right here:

    Code (CSharp):
    1. TempSensorData = float.Parse(value);
    You see, float.Parse() takes a string and changes it into a float. That means your string "value" is the temperature in string form. Try this:

    Code (CSharp):
    1. case 'T':
    2.             //temperature sensor reading
    3.             //TempSensorData = value;
    4.             TempSensorData = float.Parse(value);
    5.             TemperatureText.text = value;
    6.  
    7.             //Do Something If Temperature Falls Below 0 Degrees C
    8.             if (TempSensorData < coldLimitTemperature && lastTempSensorData > coldLimitTemperature) {
    9.                 // play the audio source
    10.                 print ("It's Chilly In Here");
    11.             }
    12.             lastTempSensorData = TempSensorData;
    13.             //Do Something If Temperature Rises Above 90 Degrees C
    14.  
    15.             break;
     
  21. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Hey no problem eisenpony I know what busy is like :) I appreciate the time and help :)
    OK I popped this in and I get this error:

    Code (CSharp):
    1. Assets/Scripts/Sending.cs(111,25): error CS0029: Cannot implicitly convert type `float' to `string'
    With this code:

    Code (CSharp):
    1. case 'T':
    2.             //temperature sensor reading
    3.             //TempSensorData = value;
    4.             TempSensorData = float.Parse(value);
    5.             //TemperatureText.text = TempSensorData.ToString ();
    6.             TemperatureText.text = value;
    7.  
    8.             //Do Something If Temperature Falls Below 0 Degrees C
    9.             if (TempSensorData < coldLimitTemperature && lastTempSensorData > coldLimitTemperature) {
    10.                 // play the audio source
    11.                 print ("It's Chilly In Here");
    12.             }
    13.             lastTempSensorData = TempSensorData;
    14.             //Do Something If Temperature Rises Above 90 Degrees C
    15.  
    16.             break;
     
    Last edited: Jan 13, 2016
  22. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    I get these errors with that?

    Assets/Scripts/Sending.cs(112,25): error CS0029: Cannot implicitly convert type `float' to `string'

    Assets/Scripts/Sending.cs(117,29): error CS0019: Operator `<' cannot be applied to operands of type `string' and `float'

    Assets/Scripts/Sending.cs(121,25): error CS0029: Cannot implicitly convert type `string' to `float'
     
  23. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    TempSensorData needs to be type float.
    Near the top of your script.

    Code (CSharp):
    1. public float TempSensorData;
    instead of
    Code (CSharp):
    1. public string TempSensorData;
     
    KnightRiderGuy likes this.
  24. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Ah Ok thanks eisenpony I don't know how I missed that sometimes the simplest stuff just totally gets un noticed.
    OK So I changed the code and the UI text is rendering out the temperature perfectly again but just to experiment at the top of the script in the:
    Code (CSharp):
    1. float coldLimitTemperature = 10.0f;
    I changed it to a temperature just a little above the current room temperature just to experiment and it did not print my message to the console. We must be missing something?

    Code (CSharp):
    1. case 'T':
    2.             //temperature sensor reading
    3.             //TempSensorData = value;
    4.             TempSensorData = float.Parse(value);
    5.             //TemperatureText.text = TempSensorData.ToString ();
    6.             TemperatureText.text = value;
    7.  
    8.             //Do Something If Temperature Falls Below 0 Degrees C
    9.             if (TempSensorData < coldLimitTemperature && lastTempSensorData > coldLimitTemperature) {
    10.                 // play the audio source
    11.                 print ("It's Chilly In Here");
    12.             }
    13.             lastTempSensorData = TempSensorData;
    14.             //Do Something If Temperature Rises Above 90 Degrees C
    15.  
    16.             break;
     
  25. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    One possibility is that the temperature reduced to exactly the temperature threshold for at least one cycle. We can improve the logic a little bit to capture this condition.

    Code (CSharp):
    1. if (TempSensorData < coldLimitTemperature && lastTempSensorData >= coldLimitTemperature)
    Notice the second operator has changed from > to >=

    Other than that, the logic seems pretty solid, though still with the exception of not noticing it's chilly if below the threshold at startup. Try making the change and confirm that the temperature is dropping below the threshold; see what we get.
     
    KnightRiderGuy likes this.
  26. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    OK Thanks I added in like this and it still does not call the Print ?
    Code (CSharp):
    1. case 'T':
    2.             //temperature sensor reading
    3.             //TempSensorData = value;
    4.             TempSensorData = float.Parse(value);
    5.             //TemperatureText.text = TempSensorData.ToString ();
    6.             TemperatureText.text = value;
    7.  
    8.             //Do Something If Temperature Falls Below 0 Degrees C
    9.             if (TempSensorData < coldLimitTemperature && lastTempSensorData >= coldLimitTemperature) {
    10.  
    11.                 // play the audio source
    12.                 print ("It's Chilly In Here");
    13.                 //StartCoroutine (ChillyVoice);
    14.  
    15.                 lastTempSensorData = TempSensorData;
    16.             }
     
  27. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    Looks like you've moved
    Code (csharp):
    1. lastTempSensorData = TempSensorData;
    inside your if block. It won't work that way; the logic requires the lastTempSensorData to always hold the last value, not just sometimes.
     
    KnightRiderGuy likes this.
  28. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    I placed it outside of the if block and still no go?
     
  29. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    You'll need to keep breaking things down then. I suggest you get comfortable doing this kind of stuff on your own since the forum makes for a bad debugging experience.

    Using the && logic operator is similar to nesting your if expressions, so if you're not sure which part is failing, you can split them up.

    You can use print to get snapshots of what's going on in your code. Unfortunately, this can lead to some large piles of text in the console. A better solution is to learn the debugger -- you can step line by line and see exactly what your code is doing.

    I wrote this really short intro to the debugger quite a long time ago. It would make a good learning project for you. http://forum.unity3d.com/threads/ranking-vector-axes-by-value.338961/#post-2204712

    Here's an example of how you could break things down without using the debugger.

    Code (CSharp):
    1. print(string.Format("TempSensorData = {0}, coldLimitTemperature = {1}", TempSensorData, coldLimitTemperature));
    2. if (TempSensorData < coldLimitTemperature)
    3. {
    4.   print("the first expression was true");
    5.   print(string.Format("lastTempSensor = {0}, coldLimitTemperature = {1}", lastTempSensorData, coldLimitTemperature));
    6.   if (lastTempSensorData >= coldLimitTemperature)
    7.   {
    8.     print("the second expression was true");
    9.   }
    10. }
     
    KnightRiderGuy likes this.
  30. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    I notice also if I do it like this then the voice Coroutine will be called constantly and I only want it to fire once. Is there a way around that?

    Code (CSharp):
    1. case 'T':
    2.             //temperature sensor reading
    3.             //TempSensorData = value;
    4.             TempSensorData = float.Parse(value);
    5.             //TemperatureText.text = TempSensorData.ToString ();
    6.             TemperatureText.text = value;
    7.  
    8.             //Do Something If Temperature Falls Below 0 Degrees C
    9.             if (TempSensorData < coldLimitTemperature && lastTempSensorData >= coldLimitTemperature) {
    10.  
    11.  
    12.             }
    13.             // play the audio source Coroutine Start
    14.             print ("It's Chilly In Here");
    15.             StartCoroutine (ChillyVoice());
    16.             lastTempSensorData = TempSensorData;
    17.  
    18.             //Do Something If Temperature Rises Above 90 Degrees C
    19.  
    20.             break;
    Screen Shot 2016-01-14 at 11.59.42 AM.png
     
  31. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    Sorry zentaiguy, it's becoming pretty clear you haven't grasped the basics of programming yet. You'll need to do a bit of work on your own before you will get good value from the forums.

    You've moved everything out of the if block -- that means there is no test to determine if something should be run or not. The call to the ChillyVoice coroutine will be run every time the MessageRecieved method is called -- which I'm guessing is A LOT.

    I said you should move the line
    Code (csharp):
    1. lastTempSensorData = TempSensorData;
    outside of the block. I didn't mention anything about the print nor the StartRoutine -- these should almost certainly be left inside the block.
     
    KnightRiderGuy likes this.
  32. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    OK But I did the following Debugs and it looks like the inside of the if is not being called?

    Code (CSharp):
    1. Debug.Log ("Checked If Cold");
    2.             //Do Something If Temperature Falls Below 0 Degrees C
    3.             if (TempSensorData < coldLimitTemperature && lastTempSensorData >= coldLimitTemperature) {
    4.                 Debug.Log ("Do Something If Cold");
    5.  
    6.             }
    7.             // play the audio source Coroutine Start
    8.             Debug.Log ("Start ChillyVoice Coroutine");
    9.             StartCoroutine (ChillyVoice());
    10.             lastTempSensorData = TempSensorData;
    11.  
     
  33. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    I just moved it out of the block to do an experiment to see if it made a difference.
     
  34. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    Yes, we already determined that when the original Debug.Log was not printed before moving everything outside of the block. We need to figure out why.

    I can't tell from here because I don't know the values of TempSensorData nor lastTempSensorData. Breaking the if statement in two pieces may help, as will printing out the values of these two variables. Unfortunately, this method gets called every time the Arduino sends a temperature message so that might be a lot of messages to comb through. That's where the debugger can help but there is a bit of a learning curve involved with that tool.
     
    KnightRiderGuy likes this.
  35. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Never mind, I think I figured out why, my temperature was not quite below what the threshold was set for seems to start the Coroutine now ;) That part is licked. :) Thanks man
    Code (CSharp):
    1. Debug.Log ("Checked If Cold");
    2.             //Do Something If Temperature Falls Below 0 Degrees C
    3.             if (TempSensorData < coldLimitTemperature && lastTempSensorData >= coldLimitTemperature) {
    4.                 Debug.Log ("Do Something If Cold");
    5.                 // play the audio source Coroutine Start
    6.                 Debug.Log ("Start ChillyVoice Coroutine");
    7.                 StartCoroutine (ChillyVoice());
    8.             }
    9.  
    10.             lastTempSensorData = TempSensorData;
    Now what if I wanted to do a voice call for if the temperature reached a "Hot" value?
     
  36. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    You can use the same pattern -- you'll need another variable to hold the hotLimitTemperature and you'll need to reverse the arithmetic bits of the logic .. something like this

    Code (csharp):
    1. if (TempSensorData > hotLimitTemperature && lastTempSensorData <= hotLimitTemperature)
     
    KnightRiderGuy likes this.
  37. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Awesome, I added it a variable at the top of my script for hotLimitTemperature ;)

    Does the rest look right?

    Code (CSharp):
    1. //Do Something If Temperature Falls Below 0 Degrees C
    2.             if (TempSensorData < coldLimitTemperature && lastTempSensorData >= coldLimitTemperature) {
    3.                 // play the audio source Coroutine Start
    4.                 StartCoroutine (ChillyVoice ());
    5.             }
    6.  
    7.             if (TempSensorData > hotLimitTemperature && lastTempSensorData <= hotLimitTemperature) {
    8.                 Debug.Log ("Start Hot Temperature Coroutine");
    9.             }
     
  38. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    Yep, I think that will work.
     
    KnightRiderGuy likes this.
  39. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Yup I just tested and it's calling both if when the temp changes....
    AWESOME eisenpony thank you SO much for your help and your patience on this :D :D :D
     
    eisenpony likes this.
  40. KnightRiderGuy

    KnightRiderGuy

    Joined:
    Nov 23, 2014
    Posts:
    514
    Just in case anyone is interested in the final results ;) Thanks again eisenpony