Go Down

Topic: Need help for communication (Read 150 times) previous topic - next topic

Ralxys

Apr 26, 2018, 12:05 am Last Edit: Apr 26, 2018, 12:06 am by Ralxys
Hello everyone, I've a problem and I need you to resolve it,

Look my code and let's me explain my aim:

Code: [Select]

void setup() {
  Serial.begin(9600);

}

void loop() {
  if (Serial.available()){
 char lumi = Serial.read();
    if (lumi == 'l')
    {
        int luminosity = analogRead(A0);
        Serial.println(luminosity);
        Serial.print("\n");
       
    }
  }
 
  if (Serial.available()){
    char temp = Serial.read();
    if (temp == 't')
    {
        int temperature_sensor = analogRead(A1);
        float mv = ( temperature_sensor/1024.0)*5000;
        float cel = mv/10;
       
        Serial.println(cel);
        Serial.print("\n");
    }
  }       
}


So, my program consist of display the temperature or the luminosity, if I type the character t or l in the Serial Monitor. However when I write t or l, the value does not display instantly and I need to spam to display this value. It's from there that I need you to help me solve my problem.

I am waiting for your reply.
Thanks.

PaulS

You see if there is serial data to read. If there is, you read a character. you see if it is a 'l'. If it is, great, you do something.

If it isn't, you read another character, and see if it is a 't'.

Does THAT make sense? If the character is NOT an 'l', well, it just might be a 't'. So, compare the character to both. Don't read again.
The art of getting good answers lies in asking good questions.

Ralxys

#2
Apr 26, 2018, 01:08 am Last Edit: Apr 26, 2018, 01:36 am by Ralxys
Hi PaulS,

Thanks for your reply, I've understand that I had to use the : if(!x).

Code: [Select]



void setup() {
  Serial.begin(9600);

}

void loop() {
  if (Serial.available()){
 char info = Serial.read();
    if (info == 'l')
    {
        int luminosity = analogRead(A0);
        Serial.println(luminosity);
        Serial.print("\n");
 
    }
    if (info != 'l'){
      (info == 't');
      if (info == 't');
    {
        int temperature_sensor = analogRead(A1);
        float mv = ( temperature_sensor/1024.0)*5000;
        float cel = mv/10;
       
        Serial.println(cel);
        Serial.print("\n");
    }
  }       
  }
}


It's work now
Thanks you !

marco_c

Code: [Select]
if (info == 'i')
{
// do something
}
else if (info == 't')
{
// do something else
}


better still
Code: [Select]
switch (info)
{
  case 'i':
  // do something
  break;

  case 't':
  // do something else
  break;
}


If you haven' seen the switch .. case statement, look it up as it is useful in these situations.
Arduino Libraries https://github.com/MajicDesigns?tab=Repositories
Parola for Arduino https://github.com/MajicDesigns/Parola
Arduino++ blog https://arduinoplusplus.wordpress.com

Go Up