Page 1 of 1

Arduino Programming for Beginners – Part 9: Text Input

Arduino Programming for Beginners – Part 9: Text Input
   5

We have learnt quite a bit in the past 8 chapters. In this ninth chapter we will start we will combine some of the things we’ve talked about and with that show you how we can read something from the Serial Monitor of the Arduino IDE, so a user can enter text or numbers.

This is the ninth part of a series of articles I’ve written to get beginners started with Arduino Programming in the programming language C, which I’ve written with the intend to teach my 13 year old nephew (Bram) to get started with the Arduino. After all, he wants to build a robot, but without some basic knowledge about programming, he won’t get far ….

Besides an introduction into the language C, the default language used for Arduino Programming, “Arduino Programming for Beginners” will also touch topics like how to setup an Arduino, get a developers environment running, and look at a few basic electronic parts which we connect to our Arduino.




Overview of this Chapter

  A complete overview of this course can be found here: Course Overview.

Input though the Serial Monitor

Now we have done quite a lot with the Serial Monitor – just so we can see the results of our programs. But all of that has been quite static, right? Everything was “fixed” and we did not deal with input from a user.

The reason why I’ve skipped that part, is that the Arduino unfortunately doesn’t have a really simple and obvious way to read text (or numbers) from the Serial Monitor as input. Pretty silly if you ask me, but you also have to keep in mind that the Arduino was not build with the intend to have a keyboard and a monitor. For learning the language however, one would need to at least see what the code is doing that you’re testing.

The Arduino is not really intended to work with a keyboard and monitor,

therefor simple printing and reading input is a little bit more challenging.

The Serial Monitor however does offer a way to send “input” to the Arduino, which the Arduino can read, indicated in the screenshot below. Here we can enter text and click the “Send” button to send a string to our Arduino.

Arduino Serial Monitor - Input field

Arduino Serial Monitor – Input field

Tip: Restarting your Arduino Program with Serial Monitor 

Each time you open the Serial Monitor, your Arduino receives a reset signal and will restart. This way you get a clean and complete output of your program.

You can also use this to restart a program. Close the Serial Monitor and press the Serial Monitor button and your Arduino program restarts. Great when you want to test a program a few times.

Restart a program: Close and Re-Open the Serial Monitor

Read String from Serial Monitor

Let’s quickly revisit how the Arduino programs work.

When your Arduino starts (connect it to USB or connect a power supply), it will right away start the program in memory. This memory will NOT be cleared when shutting the Arduino down, unlike a regular PC.

At it’s start it will run the “setup()” function right away and it will run this only once.
Once completed, it will run “loop()” over and over again.

That makes great sense, considering that the Arduino was not intended for your average program, but is for example used to read sensor data over and over again. However, this can also be serial data, and this is where our new “function” comes in play.

More advanced methods of reading input from the Serial port involves waiting for individual characters to appear, and to be added to our string, as if the Arduino was reading a “sensor” (keystrokes).

I wrote this simple function for this little course and it basically:
Displays your question, keep waiting for the user to input something and press the ENTER key.


1
2
3
4
5
6
7
8
9
String WaitForInput(String Question) {
  Serial.println(Question);
 
  while(!Serial.available()) {
    // wait for input
  }
 
  return Serial.readStringUntil(10);
}

We’ve dealt with functions before and we know how to make our own. So let’s go through this one briefly.

We first define our function as “WaitForInput” which returns a “String” – remember: the object String with capital “S” – and takes a question as a parameter. This question is also a “String” object. The returning String is what the user entered.

This means we can call this function as such:  Answer = WaitForString("My question");

Since we need to make the question visible to our user in the Serial Monitor, I’ve used “Serial.println” to first display the question we entered as a parameter for our function.

After that, you see a weird “while”-loop. Remember the “while”-loop? It will first check something, and as long as the condition is true, it will keep repeating the program block.

The condition in this “while”-loop is “not Serial.available”. “Serial.available() ” is a method of the “Serial” object, which returns the number of bytes it has read from the Serial input. If nothing was entered, then this will return zero.

Serial.available() returns the number of read bytes of the Serial port.
If no bytes where read, it returns zero.

Now remember that false was the same as zero, and that the “while”-loop wants a true condition?
With the operator not ( ! ) we can flip the zero (= false) to true.

This way, the “while”-loop will keep running as long as there has been no input on the serial.

Since we just want to wait, and really do not want to do anything in the “while”-loop, we just keep the code block empty. I just added a comment so it’s easier to read our code at a later time, and so we know we didn’t forget to type code there by accident.

Once a user types a character (which is the same as a byte), the “Serial.available()” will return a number not equal to zero. The not operator flips this to false, and the “while”-loop will be exited as the condition is no longer true.

In line 8 we use the “return” statement – which, as you might recall, is used to send information back.

But in that same line we also use the Serial method Serial.readStringUntil(10); .

Serial.readStringUntil() reads bytes that have been received from the Serial port.

It stops when it receives the character or byte that we passed as a parameter,

or when a time-out occurs (the user waited too long).

Unfortunately, if there are no bytes available before we call this method (function), it will return with nothing right away. That’s why I’ve added the “while”-loop so we wait for any input first before trying to read it.

The parameter that we pass to this method (function) is the byte (or character) which it should consider “end of transmission”, and in our case we’d like that to be the ENTER key (you could also wait for the NULL character). The ENTER key however is ASCII number 10 (see character table) and that’s why we pass the number 10.

If wanted input to stop when a user pressed the A key, then this would have been ASCII number 97 (assuming a lowercase “a”).

The output of “Serial.readStringUntil” will be send to the “return” statement right away, which in turn returns it to whichever part of the code that called our homebrew function.

Let’s glue this in a little demo program:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
void setup() {
  // set the speed for the serial monitor:
  Serial.begin(9600);
  Serial.println("Your Arduino is awake ...");
 
  String ReceivedInput;

  ReceivedInput = WaitForInput("Please enter your first name.");
  Serial.print("Your first name is: ");
  Serial.println(ReceivedInput);

 
  ReceivedInput = WaitForInput("Please enter your last name.");
  Serial.print("Your last name is: ");
  Serial.println(ReceivedInput);

  Serial.println("Your Arduino is done now and will start the loop, forever doing nothing ...");  
}

void loop() {
  // leave empty for now
}

String WaitForInput(String Question) {
  Serial.println(Question);
 
  while(!Serial.available()) {
    // wait for input
  }
 
  return Serial.readStringUntil(10);
}

To avoid endless looping, we write our test code in the “setup()” again.

First we define a variable of the data type “String” object. We will need it to capture the answer to our questions.

In the next part we will see two similar chunks of code, asking for first name, and last name.
Each time we ask a question and receive an answer from our “WaitForInput()” function.
Once received, we print some text followed by what was given as an input.

Once first- and lastname are done, a message will say that we’re done with the “setup()” function and for ever will keep doing the (empty) “loop()” function.

Read Integers from Serial Monitor

OK so we can read strings, … how about numbers?

The challenge here is that we can only read characters, which combined form a string. This can be numbers, but also characters or even special symbols. Even if we would receive only numbers, we still would have a string as an answer, which is not the same as a number.

As an example, let’s say that in the previous example, the user entered the number “3” and pressed the ENTER button.
The retuning “value” is a string, which consists of one character (byte). If we look in  the character table that I have mentioned a few times, then we see that the byte will have the value: 51. ASCII 51 = “3”. But …  51 is clearly not the same as the number “3” we actually wanted to read. So we need to convert this string to an actual number. We will focus on whole numbers – integers or “int“.

The pain of Converting a String to an Integer

You can skip this if you’d like. I’m only giving an idea here on how conversion could work, which might help developing a way of thinking which can be of use when developing your own programs in the future. By the way: there are better methods to convert text to a number!

The conversion can be a rather tedious job. Read a character, see if it’s a number and now convert it.
Let’s assume we get the number “3456” as a string an we want this to become an integer.

We would have to start at the end of the string. The first character we read is “6”, which is ASCII number 54.
In an ASCII table, numbers start at 48. So to get 6 out of that 54, we need to subtract 48 from 54.

“6” = ASCII 54, “0” = ASCII 48  =>  54 (“6”) – 48 (“0”) = 6
Answer = 6 

Next we take the number before that, which is “5”. “5” has the ASCII number 53, so here we go again, or not?
Not! Because the number “5” actually stands for “50” …. oh oh!
We need to modify our formula to keep 10’s, 100’s, 1000’s, etc. in mind.

See a pattern there? There is!
For each character, going from right to left, an extra “0” is being added.
So for 6 it’s no zero added, for 5 it’s one zero added (50), for 4 it’s two zero’s added (400) and for 3 it’s three zero’s added (3000).

To make that easier, let’s flip the string around and make “6543” from the “3456”.

Remember with arrays that counting starts with zero? Same here, since we at heart do work with an array again!

So we define our string (3456) and integer (0) and flip the string to “6543”.

Next we go through a loop, and access each element of the string array.
For the first element we take 54 – 48, which is 6.

For the second element we take ( 53 – 48 ) * 10, which is 50, and add the previous number to it: 50 + 6 = 56.

For the third element we take ( 52 – 48 ) * 100, which is 400, and add the previous result: 400 + 56 = 456.

And for the last element we take ( 51 – 48 ) * 1000, and add the previous result: 3000 + 456 = 3456.

The trick with 10, 100 and 1000 is that we can write that as 10 to the power.
Keep in mind that we actually need: 1, 10, 100, 1000.

100 = 10 to the power 0 which is the same as 1,
101 = 10 to the power 1 which is the same as 10,

102 = 10 to the power 2 which is the same as 10 × 10 (=100), and
103 = 10 to the power 3 which is the same as 10 × 10 × 10 (=1000).

Now you might not be very familiar with “to the power” yet, but you might recall when we talked about this before, and you can probably see how we can use this to make a loop to convert a string to a number. Using “to the power” is super handy in our situation, since we count 0, 1, 2, 3 in our example (real people count: 1, 2, 3, 4).

Remember:

To the power” says how many times a number is being used in a multiplication.

In other words:
How many times you must multiply the number “1” with this number.

So 10 to the power 3, is written as 103.
Reading the text above says that we need to multiply the number “1” three time with the number “10”. So that would become:

10 to the power 3  =   103   =  1 × 10 × 10 × 10  = 1,000

Some more examples:

10 to the power 1  =  101   =  1 × 10  = 10
2 to the power 4  =  24  =  1 × 2 × 2 × 2 × 2  =  16
3 to the power 2 =   32  = 1 × 3 × 3  =  9

And last but not least a funny one …. to the power “zero”, so readin our previous statement: multiply the number “1” zero times with the number “2”, so that would result in “1” as the answer. Always remember that to the power zero results in “1”.

2 to the power 0  =  20  = 1

OK now that we went totally sideways on what we were really doing: back to converting a string to a number.

Converting a String to an Integer easier

It must be obvious that this is a cumbersome thing to do … and that’s why there is a method (function) for the “String” object that does this for us in one simple statement.

The main reason why I went through the cumbersome way is to help you develop a way of thinking of we can solve problems we might run into, and see the advantage of having build-in functions or methods allowing us to re-use code and not have to re-invent the wheel over and over again.

So the “String” object has a method called “toInt()” which takes the string you entered and converts it to a integer (int).

The method “toInt()” will start with the first character of the “String”. If this is not a number, then it will stop right away and return zero (0). However, if it is a number, then it will continue remember that number and go to the next character. If that next character is not a number, it will stop and convert the number(s) it remembered, if this one is a number, then it will remember that number as well, and continue with the third character. It will keep doing this until it runs into a non-number or it reaches the end of the string.

Some examples of conversions:

toInt() examples
 String  Converted int result
 1234  1234
 12Hello34  12
 Hello1234  0
 12.3  12
 0123  123

I marked the numbers that get converted from the “String”, in the “String” column, bold so you get an idea.

Here an example, using the same function we used in our previous example:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
void setup() {
  // set the speed for the serial monitor:
  Serial.begin(9600);
  Serial.println("Your Arduino is awake ...");
 
  String ReceivedInput;

  ReceivedInput = WaitForInput("Please enter a whole number.");
 
  Serial.print("The string you entered was: ");
  Serial.println(ReceivedInput);
 
  Serial.print("Converterd to a number this is: ");
  Serial.println(ReceivedInput.toInt());
}

void loop() {
  // leave empty for now
}

String WaitForInput(String Question) {
  Serial.println(Question);
 
  while(!Serial.available()) {
    // wait for input
  }
 
  return Serial.readStringUntil(10);
}

This example looks a lot like the previous one. The only thing that is clearly different can be found in lines 13 and 14. Line 13 is obvious of course, but line 14 calls the “String” object’s method “toInt()”. See how we call the variable “ReceivedInput”, add a dot ( . ) and then type the method “toInt()”. This is the same way we call the “begin” and “print” methods of the “Serial” object.

A method of an Object is called, by calling the variabele of the object, followed by a period and the method name.

Read Float numbers from Serial Monitor

We have seen how cumbersome converting a string to a whole number can be, so you can imagine how complicated this will become when we want to convert a string to a float – a number with numbers behind the decimal point.

NOTE: If your native language is not English: the decimal separator in a programming language is a period, so one and a half is 1.5 and not 1,5.

Again our “String” object offers a method for this to do it easier. Look at this example, which is nearly identical to the integer version. The only difference is that we do not call “toInt()” but instead use the method “toFloat()“.

Remember: a “float” is a number with numbers after the decimal point.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
void setup() {
  // set the speed for the serial monitor:
  Serial.begin(9600);
  Serial.println("Your Arduino is awake ...");
 
  String ReceivedInput;

  ReceivedInput = WaitForInput("Please enter a number.");
 
  Serial.print("The string you entered was: ");
  Serial.println(ReceivedInput);
 
  Serial.print("Converterd to a number this is: ");
  Serial.println(ReceivedInput.toFloat());
}

void loop() {
  // leave empty for now
}

String WaitForInput(String Question) {
  Serial.println(Question);
 
  while(!Serial.available()) {
    // wait for input
  }
 
  return Serial.readStringUntil(10);
}

Other String object methods (functions)

We have seen two method of the “String” object just now – but there are many more. The Arduino Reference page on the String object will show you more methods of the “String” object.

Here you will find functions to, for example, trim a string (remove redundant spaces), make a string all uppercase or lowercase, see if a character or sub-string exists in the string, etc.

The Arduino Reference page shows you more of the functions and methods you can use, and is a great resource for Arduino Programming in general!

I will list a few of those other functions here. I encourage you to experiment a little with them. Read on the Arduino Reference page what they do and how they are supposed to work – it will give you practice and insight on how to use the Arduino Reference and will make searching for functions in the future easier.

Methods

Below a list of some of the more common methods (functions) of the “String” object.
The keywords (method names) link right away to the matching Arduino Reference page.

  • String() – Creates a String object
  • charAt() – Access a character at a specific position in the string
  • compareTo() – Compares two strings
  • concat() – Appends a string to the string
  • endsWith() – Tests if the string ends with a given piece of text
  • equals() – Checks if two strings are the same (case sensitive!)
  • equalsIgnoreCase() – Checks if two strings are them (not case sensitive!)
  • getBytes() – Copies the individual bytes of a string to a buffer
  • indexOf() – Locates a character or string within the string and returns it’s location
  • lastIndexOf() – Locates the last occurrence of a character or string within the string
  • length() – Returns the length of the string, not including the NULL character at the end!
  • remove() – Removes one or more characters from a string
  • replace() – Replaces a character or a sub-string of a string
  • setCharAt() – Change a character in the string to something else
  • startsWith() – Tests if a string starts with a given piece of text
  • substring() – Get a part of the string
  • toCharArray() – Converts the string in the “String” object to a “string” array of characters
  • toInt() – Converts the string to an integer
  • toFloat() – Converts the string to a float
  • toLowerCase() – Makes the string all lowercase
  • toUpperCase() – Makes the string all uppercase
  • trim() – Removes leading or trailing spaces from the string.

 

Final words …

Well, we have done 9 chapters now, introducing you to Arduino Programming in the language “C”, using a free program on your computer (the Arduino IDE) and a simple Arduino like the Arduino Uno.

I hope you enjoyed it, and I hope you picked up a few things.

You should now be able to write a simple program for your Arduino. Just keep in mind that in the long run you will remember a lot of the things you’ve learned here. Most of it will become second nature. Some aspects however, you might forget and you will need to look them up again. But don’t worry. I’ve been programming since 1978 and I still have to look up certain things – that’s why there are so many reference books and websites.

Also keep in mind that this is just the beginning …

The Arduino was created with electronics in mind. It can be used as a standalone device which handles certain tasks without you needing a lot of electronics, or needing a computer to manage whatever the Arduino will be doing.

So the next step is learning how to connect certain electronic parts, like LEDs, switches, sensors, relays, motors, and even displays.

If you look at the Tweaking4All menu on the left side, and look under “Hardware” “Arduino”, then you’ll see some examples of how I have used the Arduino in some of my projects. Projects like connecting your Arduino to the network, control LED strips with all kinds of exciting colors, how to detect light, motion or temperatures, create ambient light behind your TV and even connect a LCD display.

Eventually, with enough imagination, you’ll be building your robot …

If there is an interest for it, then please let me know in the comments below, I just might start a similar guide to electronics for the Arduino.

Also note that you’re free to ask questions in the comments below, just remember: the only stupid question, is the unasked question, and … we all had to start with nothing, so feel free to ask!

Since this is the last chapter, either go back to the beginning, or to the chapter overview.

Donation options


Donations are very much appreciated, but not required. Donations will be used for web-hosting expenses, project hardware or a motivational boost (a drink or snack). Thank you very much for those have donated already! It's truly AwEsOmE to see that folks like our articles and small applications.

Comments


There are 5 comments. You can read them below.
You can post your own comments by using the form below, or reply to existing comments by using the "Reply" button.

  • Feb 12, 2017 - 9:42 AM - Stan Comment Link

    Aplause for you Hans. But umm i dont know how i can realy write a basic program for my led strip. I just thinking of ForLoop dor a basic strip move. Any suggestion. Cus akso i need define colors in strip.

    Reply

    Stan

    • Feb 12, 2017 - 3:14 PM - hans - Author: Comment Link

      Thanks Stan! 

      Well, I usually start by writing down the steps I want to do – not in the programming language, just in normal people language .
      This forces me to rethink everything and make sure I find the correct steps. Of course, over time you’ll do most of that in your head.

      After that I see what steps I need to do in my program … so, the question is: what would you like to create? 

      Reply

      hans

  • Sep 13, 2017 - 1:00 AM - stan Comment Link

    Hi. I completely lost on this;

    String WaitForInput(String Question) { }

    Accolades??

    String name; is a defining

    String name=”Hans”;  is also defining

    But what is this;

    String WaitForInput(String Question) { }

    With accolades? I m loat deeply.. srring is nit a function like

    Void example() {

    }

    I m complete lost becauae of this i cant understand the rest of the chapter.

    Reply

    stan

    • Sep 23, 2017 - 12:11 PM - hans - Author: Comment Link

      Hi Stan,

      functions are defined as such:

      returnvalue functionname (functionparemeters) {
        function code
      }

      So the parameters are passed between the two brackets ( and ).
      The function code is written between the two accolades. See anything between two accolades as a “block”, as you might have seen with the “if” statement and such.

      The return value can be “void” (as seen in void loop() ) or a data type like char, int etc.

      Reply

      hans

      • Sep 23, 2017 - 2:34 PM - stan Comment Link

        No no we not in same case.. i say String is a data type. How we can make a function with a String?

        Reply

        stan



Your Comment …

Friendly request to not post large files here (like source codes, log files or config files). Please use the Forum for that purpose.

Please share:
*
*
Notify me about new comments (email).
       You can also use your RSS reader to track comments.


Tweaking4All uses the free Gravatar service for Avatar display.
Tweaking4All will never share your email address with others.