void loop() {
if (Serial.available()) {
byteRead = Serial.read();
String myString = String((char*)byteRead);
if(myString=="hello"){
Serial.println();
Serial.write(byteRead);}
}
}
void loop() {
if (Serial.available()) {
byteRead = Serial.read();
String myString = String((char*)byteRead);
if(myString=="hello"){
Serial.println();
Serial.write(byteRead);}
}
}
please read the thread on how to post code so it looks like this:
... code here
You could try using this:
byteRead = Serial.read();
reads a single char, so no matter how much casting to other data types that you do
if(myString=="hello"){
is never going to work.
void loop() {
if (Serial.available()) {
byteRead = Serial.read();
String myString = String((char*)byteRead);
if(myString=="hello"){
Serial.println();
Serial.write(byteRead);}
}
}
I'm not much of a CPP programmer but as I see it String myString creates a new string every time that the code goes through the loop. It will never remember the previous value.
If you move it outside the loop(), it will be global and it will remember the last value.
You're still overwriting that previous value though every time that the code executes String myString = String((char*)byteRead);
As said, not much of a CPP programmer so no idea how to manipulate String (and too lazy to look it up).
It is recommended NOT to use Strings (capital S) in the small memory of an Arduino as they can cause memory corruption.
Have a look at the examples in Serial Input Basics
You can use the strcmp()
function to cpmapre strings (small s). However if you just want to compare a single char you can do it with something like
if (myChar == mystring[3]) {
...R
Yeah, except in this case, it's a very small program and the OP seems to be much more comfortable with String Objects. In your case, either way is fine OP. Whatever you feel more comfortable with.
A simple example of capturing characters being sent and making a 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="";
}
}