Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert serial.read() into a useable string using Arduino?

Tags:

arduino

I'm using two Arduinos to sent plain text strings to each other using newsoftserial and an RF transceiver.

Each string is perhaps 20-30 characters in length. How do I convert Serial.read() into a string so I can do if x == "testing statements", etc.?

like image 551
Joe Avatar asked Apr 17 '11 22:04

Joe


People also ask

What does serial read () return?

Returns. The first byte of incoming serial data available (or -1 if no data is available).

What does serial read () do?

The Serial. read( ) function will read the data from the data byte and print a message if the data is received. The data is sent from the serial monitor to the Arduino.

How do you read a serial read string?

"Serial. readString()" read the serial data in string.It mean for "String a=Serial. readString();" command "a" store string.In the picture there are two photos one is ardino IDE serial monitor, another is proteus virtual terminal.

What is the use of available () method in serial library for Arduino?

This code sends data received in one serial port of the Arduino Mega to another. This can be used, for example, to connect a serial device to the computer through the Arduino board.


2 Answers

Unlimited string readed:

String content = ""; char character;      while(Serial.available()) {      character = Serial.read();      content.concat(character); }        if (content != "") {      Serial.println(content); } 
like image 199
user1415516 Avatar answered Oct 10 '22 23:10

user1415516


From Help with Serial.Read() getting string:

char inData[20]; // Allocate some space for the string char inChar=-1; // Where to store the character read byte index = 0; // Index into array; where to store the character  void setup() {     Serial.begin(9600);     Serial.write("Power On"); }  char Comp(char* This) {     while (Serial.available() > 0) // Don't read unless                                        // there you know there is data     {        if(index < 19) // One less than the size of the array        {            inChar = Serial.read(); // Read a character            inData[index] = inChar; // Store it            index++; // Increment where to write next            inData[index] = '\0'; // Null terminate the string        }     }      if (strcmp(inData,This)  == 0) {        for (int i=0;i<19;i++) {             inData[i]=0;        }        index=0;        return(0);     }     else {        return(1);     } }  void loop() {     if (Comp("m1 on")==0) {         Serial.write("Motor 1 -> Online\n");     }     if (Comp("m1 off")==0) {        Serial.write("Motor 1 -> Offline\n");     } } 
like image 21
magma Avatar answered Oct 10 '22 22:10

magma