Thursday, June 19, 2008

USB Communication

Now that the Arduino can control the mechanics, I need to get the Arduino to accept input via the USB connection. The Arduino already has serial communication libraries, so it's a matter of checking for a message from the computer, parsing it, and setting the chassis object.

Here's a new Arduino main program to replace the old one.

I have no idea if there is an established protocol for this sort of thing: so far searching for any info on USB communication in C++ has been fruitless, so I'm making this up as I go along. I want the messages to be short to keep things fast and simple. Since the USB connection works as a sequence of bytes, it's easiest to parse the input as characters. I'm going to use two bytes as a message, the first byte will be the header, and currently that'll only involve two values: one for steering, and one for throttle. The second byte will be the value. It would be possible to do this all with one byte, but with two bytes I get a larger range of possible values, and some flexibility if I want to add additional message types, as there are plenty more possible header values. For ease of testing and debugging, I'm only going to use characters that are represented on a qwerty keyboard. That way I can type messages directly into the Arduino compiler's Serial input to test the system.
Looking at an ASCII table, the lowest value that is not a special character is the spacebar: #32. The highest is #126, the tilde ~. I'm going to reserve the space as a sort of "Null" message - unused whitespace. So, the throttle header will be #33 , the ! character, and the steering header will be #34, the " character. The data will range from #35 to #126. For example:

!# = full reverse
!Q = zero throttle
!~ = full throttle

"# = maximum left turn
"Q = center steering
"~ = maximum right turn

Now I need to write a program for the computer to generate these messages.

No comments: