My Code Doesn't Work

Hello,
I'm wondering why this code snippet wasn't working. (It's probably something obvious which I didn't notice. That happens all the time! :slight_smile: )

String var = "asdfqwerty";

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

void loop() {
var = Serial.read;
Serial.println("What is your name?");
while (var == "asdfqwerty") {
delay(50);
}
}

Thanks,
-ChopinCJ-

What is is supposed to do?

That code makes no sense and won't even compile, which might explain why it doesn't work.

Please read and follow the instructions in "How to use this forum".

-ChopinCJ-:
String var = "asdfqwerty";
...
var = Serial.read;

I think this forum already contains 1000 threads discussing why you should NOT use the "String" class type in your program as well as another 1000 threads discussing "Serial input basics" and leading with a link to that thread:
https://forum.arduino.cc/index.php?topic=288234.0

Do you possibly think we need also 1000 threads discussing the combination of "String" and "Serial input basics"?


How to use this forum - please read.
and
Read this before posting a programming question ...

Try this, not perfect but might do a bit like you want

String var = "";

void setup()
{
  Serial.begin(9600);
  Serial.println("What is your name?");
}

void loop()
{
  if (Serial.available() > 0) var += (char)Serial.read();

  if (var == "abc")
  {
    Serial.println("right");
    var = "";
  }
  if (var.length() > 3) 
  {
    var = "";
    Serial.println("What is your name?");
  }    

}

Christmas Gift :slight_smile:

I'm wondering why this code snippet wasn't working

Not sure what your code is supposed to do, but below is some simple serial test code that includes character capture and comparison.

// zoomkat 8-6-10 serial I/O string test
// type a string in serial monitor. then send or enter
// for IDE 0019 and later

int ledPin = 13;
String readString;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT); 
  Serial.println("serial on/off test 0021"); // so I can keep track
}

void loop() {

  while (Serial.available()) {
    delay(3);  
    char c = Serial.read();
    readString += c; 
  }

  if (readString.length() >0) {
    Serial.println(readString);

    if (readString == "on")     
    {
      digitalWrite(ledPin, HIGH);
      Serial.println("LED ON");
    }
    if (readString == "off")
    {
      digitalWrite(ledPin, LOW);
      Serial.println("LED OFF");
    }
    readString="";
  } 
}