String Incoming_value = "";
int led =13;
void setup() {
Serial.begin(9600);
pinMode(led,OUTPUT);
}
void loop() {
if(Serial.available()>0){
Serial.println("enter on or off");
Incoming_value=Serial.readString();
Serial.println(Incoming_value);
if(Incoming_value=="on"){
digitalWrite(led,HIGH);
delay(1000);}
else if(Incoming_value=="off")
digitalWrite(led,LOW);
}
}
why are you printing a prompt -- "enter on or off" -- after received data is available? shouldn't the prompt be generated in setup() for the first time and after receiving subsequent messages?
why is there a 1 sec delay after turning on the led? the led is only being turned off after receiving an "off"
yes you are right but this is not the problem.
The problem is when i click on button 1 to send an (on) message, the serial monitor reads the on message in a strange way.
As you can see in the picture i provided, at first i send from the serial monitor and it worked perfectly but when i click on the android app to send a an on or off message, the serial monitor prints something strange like oo and oww.
i'm not that familiar with reading "Strings" using readString(). it's not obvious to me that the String is deallocated or overwritten when used this way
have you considered using readBytesUntil() and a char buffer, char buf [80];
, which doesn't rely on a timeout
can you write for me the code using readbytesuntil() and what should i do in app inventor
enum { Off = HIGH, On = LOW };
char buf [80];
// -----------------------------------------------------------------------------
void
loop (void)
{
if (Serial.available ()) {
int n = Serial.readBytesUntil ('\n', buf, sizeof(buf));
buf [n] = '\0';
if (! strcmp (buf, "on"))
digitalWrite (LED_BUILTIN, On);
else if (! strcmp (buf, "off"))
digitalWrite (LED_BUILTIN, Off);
else
Serial.println (buf);
}
}
// -----------------------------------------------------------------------------
void
setup (void)
{
Serial.begin (9600);
pinMode (LED_BUILTIN, OUTPUT);
digitalWrite (LED_BUILTIN, Off);
}
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.