Controlling Arduinos through the Serial Port

Prelude: I’m not a coder or computer science whiz, so my forays into programming are fraught with internet searches of how to do this or that and reading and rereading references. I am certainly no expert.

Something I really wanted to do with my arduino was send it commands through the serial port– e.g. I wanted to be able to type ‘r50’ into the serial port and turn the red LEDs to 50% intensity. This is useful for a number of reasons, not just commanding an arduino hooked up to your computer via a USB connection. You could imagine wanting to send commands over wifi, bluetooth, or from a raspberry pi. But you still need the arduino to correctly understand what you’re telling it.

This short script doesn’t really exist on the internet! At least, I couldn’t find it. I found something that got close in a forum somewhere (actually right here) but it took a bit of tweaking to get working correctly.

It basically looks like this:

//initialization for readCommand()
String content = “”;
char character;

void readCommand() {
while (Serial.available()) {
character = Serial.read();
if (character == ‘\n’) {
writeCommand(content); //do something with command string
content = “”;
}
else content.concat(character);
}
}

The idea here is that you read the characters one at a time, and concatenate them into a string. This is because there is no command which will read a string from the serial port. The concatenation part was what I found in the forum linked above.

The tricky part is how to know when to stop reading characters. When you are typing into the serial port on your computer, ‘\n’ signifies that you’re starting a new line– i.e. you’ve hit enter. So if you want to read everything you enter into the serial port, you better have you code use ‘\n’ as your stop character, otherwise the function will behave erratically as it ends reading the command early but still has to process the extra character/s (i.e. the serial port will still be available.)

It’s a little different if say, a raspberry pi is writing something to the serial port. It’s more precise, I guess, because it doesn’t send the ‘\n’ character. In this case, I would use an artificial end character for the function to recognize. For instance, end every command with a period (‘.’) and swap that out for ‘\n’.

Hope this helps some computer-science-poor person (like me) figure this out.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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