Go Down

Topic: Serial read to a string (Read 324 times) previous topic - next topic

N314

Hi,

Im trying to send a word to my arduino perform an action based on that word.
is there any way I can use "Serial.read()" into a string?

dc42

Not directly. Personally, I'd avoid using String because of the variable memory usage and memory fragmentation that it causes. Since you know what words you are expecting, you can use a fixed length buffer to read the serial data into, taking care not to let the buffer overflow if you receive unrecognised data.
Formal verification of safety-critical software, software development, and electronic design and prototyping. See http://www.eschertech.com. Please do not ask for unpaid help via PM, use the forum.

zoomkat

Simple code to capture characters sent from the serial monitor into a string.

Code: [Select]

// zoomkat 7-30-11 serial I/O string test
// type a string in serial monitor. then send or enter
// for IDE 0019 and later

String readString;

void setup() {
  Serial.begin(9600);
  Serial.println("serial test 0021"); // so I can keep track of what is loaded
}

void loop() {

  while (Serial.available()) {
    delay(1);  //delay to allow byte to arrive in input buffer
    char c = Serial.read();
    readString += c;
  }

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

    readString="";
  }
}
Google forum search: Use Google Advanced Search and use Http://forum.arduino.cc/index in the "site or domain:" box.

Go Up