Tuesday, September 3, 2013

Receiving Serial Data with an Arduino

In this post I will demonstrate a few ways to receive data via serial on an Arduino from a computer. I received a question about this on one of my other posts and decided to make a post on this topic.

First off, read the official Arduino documentation on this HERE. You may very well not need this after you do.

Second, there are some official Arduino examples that come with the IDE. I won't replicate something that is already there.

Third, if this is not what you are looking for (perhaps you were looking for serial between 2 Arduinos). Check my labels. There is one called communication that might interest you. Now let's get to it.

I'm going to assume you already know how to send data to your computer. It isn't hard to get pretty things to pop up on the Serial Monitor. If not, check out the serial examples under basics in the IDE.

To send data from the Serial Monitor you need only type something into it and hit enter. Most terminal emulators probably work the same way.

Get my Serial Test sketches HERE. I will just comment on the methods from the Flash_the_LED sketch. It was made for a previous post but will work just fine for this. You send it a number from the Serial Monitor and it flashes the LED that many times.

while (Serial.available())
This is the first important part of the sketch. This is a pretty typical scenario. You only want to check for new values when there is something in the Serial buffer. If there is nothing, Serial.available() will return 0 and the statement will be false. Remember 0 is false. Anything else is true.

val = Serial.parseInt();
This part receives 2 bytes from the serial buffer and converts them back from ascii to the number you want. If you are using a terminal emulator and are having problems, this might be it. I believe the Serial Monitor puts it through an ascii conversion, but other programs might not.

An int value is made up of 2 bytes in ascii format. That is why you need the parseInt(). If you are just receiving one byte, just use Serial.read(). That receives one byte. You can also piece bytes together yourself and do individual bits in a byte, but that is another post. That should about cover it for this topic.

Serial communication can get complicated, but the basics are simple on an Arduino. Play around with it. Look over the Arduino examples and MINE. Hang out on the Arduino playground and forum. You will soon be an Arduino communication master.


No comments:

Post a Comment