Friday, August 20, 2010

serial communications

Past few days have seen some work on interfacing the Arduino with the computer so I can read the distance sensor and check the calibration. The solarbotics IR distance sensor should, according to their documentation, be pretty close to what they mentioned. It's always good to verify this though.

The Arduino's programming environment comes with a serial monitor, which can be used to send and receive data from the USB connection, which on my Mega is port 1 out of 4. The big problem is, it has problematic limitations.

The softwareSerial library has three primary commands--write, read, and print. Read() is used to read the buffer on the chip, and take commands into the program. Write() and print() will send data from the chip, write() sends binary data, and print() sends ASCII characters. Read() takes ASCII too, and this is where the trouble starts.

Read() will only take ONE(that's 1) byte of data. That's a single character, so if you're using letters for commands, no big deal. Problem is, I'm trying to send DATA, specifically, integers for the position of a servo. An int is TWO bytes, and a single read() will only get the first. There seems to be half a dozen ways to get around this, from messing with kinds of bytes or with arrays, to what I think will be the easiest, using a string. For this, you build a loop for reading the buffer, and appending the data onto a string, which you can then use atoi on to get your integer.

Single digit integers can be done however, by simply subtracting the CHARACTER '0'(zero, since the font looks wonky) from the value passed along. Since numbers in the ASCII table start at 48(zero), this shifts everything over to where it lines up with the actual numbers. Only works for one digit though. You could also get away with typing in the character corresponding to the number you want, but that would be too much work for most.

I'm still waiting on a response to a query on getting the string library the sample I saw working, next post will either be on more serial communication, or on hooking up optical mice and getting a delta position signal off for dead reckoning.

No comments:

Post a Comment