0

How do I push an array of 12 bytes down the serial port?
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

How do I push an array of 12 bytes down the serial port?

by shobley on Mon Mar 02, 2009 3:53 pm

...with the minimum of fuss?

I have an array of 12 bytes, and I want to push these down the serial port as a binary packet.

The only way I've come up with so far is to call Serial.Print(char, BYTE) 12 times - is there a better way?
http://www.stephenhobley.com
http://www.youtube.com/shobley
For all your laser harp, tesla coil, and killer robots from outer space needs.
shobley
 
Posts: 184
Joined: Fri Sep 07, 2007 5:16 pm

Re: How do I push an array of 12 bytes down the serial port?

by westfw on Mon Mar 02, 2009 6:14 pm

Code: Select all | TOGGLE FULL SIZE
for (i=0; i < 12; i++) {
  Serial.print(myarray[i], BYTE);
}
(which is sorta what you said.)

If your binary data will never contain a zero, you can give your array a 13th "terminating" element set to zero and use the string version of Serial.print:
Code: Select all | TOGGLE FULL SIZE
myarray[12] = 0;
Serial.print((char *)myarray);
But that's relatively evil...
(performance-wise it won't matter, since the string print will do the equivalent of the first loop internally anyway.)

westfw
 
Posts: 1603
Joined: Fri Apr 27, 2007 1:01 pm
Location: SF Bay area

Re: How do I push an array of 12 bytes down the serial port?

by Ran Talbott on Mon Mar 02, 2009 11:13 pm

If there's a 0x00 byte in middle of the array, "Serial.print((char *)array)" will interpret it as a string terminator. This will almost certainly produce less-than-pleasing results.

Another pitfall to watch out for is how the receiver determines where each array begins and ends. Many techniques have been invented over the years for doing this, each with their own advantages and disadvantages. Which one you should use depends heavily on the particular circumstances of your application, but not using one means you're probably going to have problems keeping the sender and receiver in synch.

Ran
Ran Talbott
 
Posts: 57
Joined: Thu Feb 19, 2009 1:32 pm

Please be positive and constructive with your questions and comments.