Oct
14

How to Read Strings from Serial in Arduino

10/14/2023 04:30 PM by Admin in Iot


In this Quick tutorial we will look into how can we read user input strings from the Arduino Serial Monitor or other serial terminals. Quick steps.

  • Define serial_buffer_len which will be max user input you are expecting.
  • Set desire serial baud rate.
  • Check if we have Serial data available using Serial.available().
  • Call user defined read_serial_input() function to load the serial_buffer.
//Serial buffer
#define serial_buffer_len  80
char serial_buffer[serial_buffer_len];
String user_input = "";

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

void loop() {
	if (Serial.available() > 0){
		if (read_serial_input(Serial.read(), serial_buffer, serial_buffer_len) > 0) {
			user_input = String(serial_buffer);
		}
		Serial.println("serial user input:" +user_input);	
	}
}

// funtion to read user serial input
int read_serial_input(int read_ch, char *buffer, int len) {
    static int pos = 0;  
    int rpos;   
    if (read_ch > 0) {
        switch (read_ch) {
            case '\r': // Ignore CR
                break;
            case '\n': // Return on new-line
                rpos = pos;
                pos = 0;  // Reset position index ready for next time
                return rpos;
            default:
                if (pos < len-1) {
                    buffer[pos++] = read_ch;
                    buffer[pos] = 0;
                }
        }
    }
    return 0;
}

After uploading the sample code open serial monitor and input something like hello world and then you will see it printed in the serial monitor. This is very useful code snippet incase you want to input strings from user and want to perform actions on it.


Your Thoughts

Search
SPONSOR
CRYPTOWATCH
FOLLOW US
ANNOUNCEMENTS

New tool added : SVG Zoom Dimension Calculator.

SPONSOR