Package and transfer data by USB serial connection to PC

11 Jan 2017

Hi,

For a data acquisition project I'd like to transfer data sampled by ADC to the PC by USB-serial connection. So far I used the USBserial library (because it seems to work faster and smoother than the standard serial lib). To transfer the data I use putc(). Although it transfers it in 1 byte packages, I need to separate the 12-bit ADC data in two 1 byte packages ( because of putc).

The connection and the transmission of the 2 x 1 byte packages by a USBserial works fine, but what is best way to know in which order the packages are transmitted to re-assemble the data in the right order in the PC?

Would appreciate a quick suggestion how to do it.

Olli

19 Jan 2017

Olli,
You don't have to worry about the order in which the "packages" arrive, as they will arrive in exactly the same order that you send them.

So, simply do putc( ADC&0xff); putc( (ADC>>8)&0x0f); and on the receive side it will always arrive in that order.

If you are concerned that somehow a character may get lost and you get out of sync, send a sync character:

putc(0x7e); // sync
putc(ADC&0x3f); // lo 6 bits
putc( (ADC>>6)&0x3F); // hi 6 bits


Since you are sending only 6 bits of data each time, the sync character 0x7e can never occur in your data.

On the the receive side, you first wait for the sync character

while ( getc() != 0x7e ) ; // hunt for start of frame
int lo = getc(); // found frame, now read lo 6 bits
int hi = getc(); // found lo, now read hi 6 bits
int ADCvalue = (hi<<6)|lo;


However, you are using 3 bytes instead of 2, so it's a 50% increase in bandwidth. So you could create frames of, say, 256 samples...

One more thing you may find useful is to add 0x20 to your 6-bit values, which makes all of them printable ASCII. On the receive side, you subtract the 0x20 before assembling the bits. This is handy when watching output on a terminal screen.

Let me know if it helps,
Nicolas