How to read Strings – Control a LED

Reading strings in Arduino is a very important concept to master because it will allow you to communicate with the Serial COM in a more understandable way (instead of byte or ASCII).

There are also other benefits when using strings for serial communication, such as:

  • Converting strings to other data types using the toInt(), toFloat() functions.
  • Easier to send strings in I2C communications.
  • Easier to work with other programs developed in other programming languages such as Python or Java.

Don’t have an Arduino, click here to purchase one using our affiliate link.


Topics:

Link to each section.

1- Understanding the Serial COM

2- Using the Serial COM to read Strings

3- Using user input to control LEDs

4- Video Section

Understanding the Serial COM

Serial communication is the process of sending data one bit at a time, sequentially, over a communication channel or computer bus.

Serial communication example

Serial is used for communication between the Arduino board and a computer or other devices. All Arduino boards have at least one serial port (also known as a UART or USART): Serial. It communicates on digital pins 0 (RX) and 1 (TX) as well as with the computer via USB. Thus, if you use these functions, you cannot also use pins 0 and 1 for digital input or output.

When communicating with your Arduino via USB through your computer we use the Serial monitor.

Arduino Serial Monitor

The Serial Monitor is a graphic interface built-in in the Arduino IDE, it allows us to send data as bytes from the computer to the Arduino.

We can find the Serial Monitor window by clicking on the magnifying glass icon on the upper right corner, or by using the short keys [CTRL+SHIFT+M] for Windows or [COMMAND+SHIFT+M] for Mac.

In order to enable the Serial Communication in your Arduino sketch code, you need to type the following on the setup section.

  Serial.begin(9600);

Where the 9600 represent the Baud Rate, which is the number of bytes per second that are going to be transferred through the Serial. By default, the standard Baud Rate for simple applications is 9600 bauds.

Using the Serial COM to read Strings

Like we mentioned before, the Serial is only capable of storing and sending data in the form of bytes, but the Arduino IDE has a built-in function called Serial.readString() which allows converting the information received in bytes to a string. Which is easier to manipulate.

Storing the data as a string [Example]

serialReading = Serial.readString(); 

Since we also know that the Serial Monitor is a graphic interface for communicating with the Arduino, we can also make the Arduino communicate with us through it, to do so we the Serial.println(“”) function to display text in the Serial Monitor.

The Serial.println(“”) function will automatically add a line break (newline) to the end of the string that we would like to display, in case you would like to print the same text without the newline then use Serial.print(“”).

PRO TIP:

Since the Arduino static random access memory (SRAM) is very limited, so using multiples Serial.print(“”) can make your code run slow or misbehave due to the lack of memory, so to avoid that you need to do the following:

Serial.println(F(your_text))
//OR
Serial.print(F(your_text))

Displaying text in the Serial Monitor [Example]

Serial.println("TURN THE LED [ON/OFF]: ");

Since we depend on user-based input, and we also know that the loop function goes over and over, a good to make the code wait for the user input is to join the following two functions:

  • Serial.available(): which provides us with the number of bytes available in the Serial.
  • while(): this will allow us to repeat a task, in this case, a “hold” based on a condition (bytes available on the Serial).

Waiting for a user entry [Example]

 //WAITING FOR USER INPUT
 while(Serial.available() == 0);

Now, we know how to ask for the input, wait for the user entry, and store the entry as a string, but there is a final piece that we are missing. And is the most important one, and that would be the string manipulation.

Once the Arduino converts the series of bytes into a string, it adds at the end a break or newline character, now this character is important for the Arduino because it allows it to know where the string ends (E.O.L or end of line), but not for us because we want to use the string as it was sent.

So we use the string manipulation to remove that last character, and we do so using the .Remove() function. Which requires two parameters to operate which are the initial position, and the number of characters to be deleted.

//Syntax
myString.remove(index, count)

Character removal from a string [Example]

 //DELETING THE LAST CHARACTER 'ENTER'
 if(serialReading.length() > 0){
      //DELETE FROM LAST CHARACTER
      serialReading.remove(serialReading.length()-1, 1); 
  }

Now, we can join all the pieces together and it should look something like this:

Reading strings using the Serial COM [Example]

 //ASKING FOR USER INPUT
 String serialReading;
 Serial.println("TURN THE LED [ON/OFF]: ");

 //WAITING FOR USER INPUT
 while(Serial.available() == 0);

 //STORING INFO IN VARIABLE (serialReading)
  while(Serial.available()){
      //SMALL DELAY TO MAKE SURE INFO GETS STORE CORRECTLY
      delay(2);
      serialReading = Serial.readString(); 
  }
 
 //DELETING THE LAST CHARACTER 'ENTER'
 if(serialReading.length() > 0){
      //DELETE FROM LAST CHARACTER
      serialReading.remove(serialReading.length()-1, 1); 
  }

Observation:

The reason we use the Serial.readString() function inside a while loop with the Serial.available() function is to ensure that meanwhile there is info in the Serial it gets stored in our variable.

Using user input to control LEDs

The reason or main purpose of using the Serial COM to store a user entry is to do something with it. In this case we’ll control a LED, the Arduino has a built-in LED in the PIN 13, but in this case, we built a simple circuit with a conventional LED instead.

If you would like to build the circuit, then you’ll need the following components: (If you don’t feel to free to skip to the end)

Required Components
  • LED (5mm)
  • 220 ohm Resistance [Max: 1k ohm Resistance]
  • Protoboard
  • x2 Jumper wires
Led control circuit
Circuit connection:
LED control circuit connections

The yellow cable is connected to the PIN 5 of the Arduino, but feel free to use whichever PIN you would like.

The circuit connection layout was made using an open-source, free software called Fritzing. Click here to download.

Now that we have the circuit built, let’s continue with the coding. We need to set the pin mode of the PIN that we’ll be using to control the LED, in this case, we need the PIN to work as an OUTPUT.

For the code to be more general or customizable, we created a variable called LED, which stores the PIN that we’re using to control the LED.

//DEFINE LED as PIN 5, which would be the PIN that we're going to be sending digital signals (HIGH/LOW) 
int LED = 5;

If you didn’t build the circuit, instead of setting LED equals to 5, set it to 13. The PIN 13 controls the Arduino’s onboard LED.

LED pinMode and initial state definition [Example]

void setup() {
  // put your setup code here, to run once:

  //DEFINE LED as a DIGITAL OUTPUT
  pinMode(LED, OUTPUT);
  //INITILIAZE THE SERIAL COM
  Serial.begin(9600);
  //DEFINE AN INITIAL STATE, LOW FOR OFF
  digitalWrite(LED, LOW);
}

We also define an initial state to the LED, so that we can compare the difference after a user entry. In this case, we’re setting that initial state to LOW or OFF.

For the control cycle, we are going to use if statements.

//Syntax
if (condition) {
  //statement(s)
}

LED control using if statements [Example]

//TURNING ON AND OFF THE LED BASED ON THE INPUT
 if(serialReading == "ON"){
  digitalWrite(LED, HIGH);
  Serial.println("LED IS NOW ON!");
 }

 if(serialReading == "OFF"){
  digitalWrite(LED, LOW);
  Serial.println("LED IS NOW OFF!");
 }

FULL CODE

We have successfully revied all of the parts required for this simple sketch, so by joining them together, we should have the following result.

You can also download the full code by clicking here.

//https://www.Roboperks.com 
//"Taking ideas to the next level"
//Arduino Tutorials
//READING FROM SERIAL AND TURNING ON/OFF A LED (READING AN INPUT FROM SERIAL AND EXECUTING AN OUTPUT)

//DEFINE LED as PIN 5, which would be the PIN that we're going to be sending digital signals (HIGH/LOW) 
int LED = 5;

void setup() {
  // put your setup code here, to run once:

  //DEFINE LED as a DIGITAL OUTPUT
  pinMode(LED, OUTPUT);
  //INITILIAZE THE SERIAL COM
  Serial.begin(9600);
  //DEFINE AN INITIAL STATE, LOW FOR OFF
  digitalWrite(LED, LOW);
}

void loop() {
  // put your main code here, to run repeatedly:
  
  //ASKING FOR USER INPUT
  String serialReading;
  Serial.println("TURN THE LED [ON/OFF]: ");
 //WAITING FOR USER INPUT
 while(Serial.available() == 0);
 //STORING INFO IN VARIABLE (serialReading)
 while(Serial.available()){
  //SMALL DELAY TO MAKE SURE INFO GETS STORE CORRECTLY
  delay(2);
  serialReading = Serial.readString(); 
 }
 
 //DELETING THE LAST CHARACTER 'ENTER'
 if(serialReading.length() > 0){
  //DELETE FROM LAST CHARACTER
  serialReading.remove(serialReading.length()-1, 1); 
  }
  
 //TURNING ON AND OFF THE LED BASED ON THE INPUT
 if(serialReading == "ON"){
  digitalWrite(LED, HIGH);
  Serial.println("LED IS NOW ON!");
 }

 if(serialReading == "OFF"){
  digitalWrite(LED, LOW);
  Serial.println("LED IS NOW OFF!");
 }
} 

Video Section

We also created a video tutorial for this code, we would highly recommend you to watch it because it will provide you additional information that will ensure that you have a solid foundation of the concepts reviewed here.

If you found this helpful, feel free to like the video and subscribe to our YouTube channel. Thanks

Hope this was helpful. See you in the next post.

Thank you for reaching this far!

Let Us share great content with you.Don't miss out on the latest project updates, blogs and more...

Leave a Reply