hi....
i want to write a code which asks the user to input the value either "john" or "Mike"... if the user enter "John" the port send "Led is on" and turn "on" the led on pin 13 and when the use enter "Mike" the port send "Led is Off" and turn "off" the led and then whole process starts again.
but the problem is that when i run the code it asks for only one time and when i enter "John" it turn the led "On" but don't get start the process again...
here is the code
int ledPin = 13;
String content = "";
char character;
void setup()
{
//Create Serial Object
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop()
{
if (Serial.available())
{
character = Serial.read();
content.concat(character);
if (content == "John")
{
Serial.println("Led is On");
digitalWrite(ledPin, HIGH);
}
else if (content == "Mike")
{
Serial.println("Led is Off");
digitalWrite(ledPin, LOW);
}
}
}
You don't reset the String, so you're always "adding" to it.
i have used String stringOne = ""; to clear the string but it didn't worked...
can you tell me what to write so it can clear the string?
i have used String stringOne = ""; to clear the string but it didn't worked...
Yes, but that's a one-off.
You need to do it as soon as you've got a match.
Of course, if you don't get a match and the user just enters junk, you've got big problems - you just keep concatenating until you run out of RAM.
I don't use String.
Simple code you can modify and try.
// 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);
}
if (readString == "off")
{
digitalWrite(ledPin, LOW);
}
readString="";
}
}