LESSON 12: Simple and Easy Way to Read Strings, Int’s and float’s Over Arduino Serial Port

One of my biggest frustrations in programming is the confusion over inputting data over the serial port. There are lots of Arduino tutorials that make it much harder than it has to be. There are many difficult and complicated ways you can read data over the serial port, but luckily there is an easy way. While we touched on this briefly in earlier videos, it is such an important topic I want to focus on it in this lesson.

In order to read data over the serial port,  you first have to determine what type of data you will be expecting. Almost all possible needs can be covered by three simple data types. Usually you can make just about any project work with Strings, Float’s, or Int’s. So, you need to know how to read these three data types over the serial port. The easiest way to read a string of text is using the Serial.readString() command. The easiest way to read a Float is with the Serial.parseFloat() command and the easiest way to read in Int with with the Serial.parseInt() command.

To practice this, lets do the following. Write a program that will promt the user for his age, for how much he weighs, and then how tall he is in feet. Then print out a nicely formatted output that relays that information back to the user.

In order to do this the first thing we must do is decide what type of variables to use for each of these three pieces of data.  For the person’s name, you naturally would use a String, since a name is a string of text. To store the weight, we would just about always round to the nearest whole number so it would make sense to use an Int for this. On height, we would not normally round to the nearest foot . . . we might want to say that someone was 5.5 feet tall. In this case we should use a float, since we want the decimal numbers. So, we would then declare these variables the suitable type and then read them in using the corresponding commands.

Also, remember when you are going to read data from the serial port you must do three things: 1) Prompt the user for data, 2) wait for him to input the data, and 3) read the data. This should be review as we have done this in several earlier lessons.

Try and write the program yourself, but if you get stuck you can look at the code below that I wrote for this problem.

OK, hopefully you were able to get this working. Now time for you to go solo and write a program on your own.

Prompt the user for his name, and his weight in pounds. Then use that to calculate his weight in Ounces, in grams, and in carats. Note, that is carats, like they measure diamonds, not carrots like you eat.

After doing these calculations send a message to the user greeting him by name and telling him is weight in pounds,  in ounces, in grams,  and in carats.

In order to do this assignment you will have to do some research to figure out how to do the conversions.