Arduino String to Integer

So I already talked about how to read strings from the serial port, but I didn’t talk about how to interpret these strings to perform actions. A pretty standard and useful technique is to have commands with a character-integer structure, in which a common command might be ‘r255’. ‘r’ is a pointer for the type of command, say configuring a red LED, and then ‘255’ would be the command for that type, say analog writing the red LED to 255 (i.e. turning it on at full brightness). Another common command might be ‘p0’, in which ‘p’ stands for power and ‘0’ turns your device off. This makes your commands very simple and standardized, but also gives you plenty of room for commands (52 types of commands and basically infinite numerical options within them).

But you’re reading this command as a string! It is easy to extract the first character, but I found it difficult to extract the integer from the string. I ended up writing some messy code that read the integers (as characters) one by one and then did some math to combine them into a whole number. It looks like this, where command is the command string:

int num = 0;
for (int i = 1; i < command.length(); i++) {
int val = command[i] - '0';
int power = command.length()-i-1;
int multi = 1;
for (int j = 0; j < power; j++) multi = multi*10;
num = num + val*multi;

It’s ugly! And silly. (Though it works!) One of my coworkers cleverly found a built-in arduino function that will turn strings into integers! I’m glad he did, though it’s weird that I couldn’t find it originally. A google search for “arduino string to integer” doesn’t bring it up even though the function is literally “string.toint”.

So spread the word! To convert a string into an integer use StringToInt. You can find arduino’s example code here.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s