Still Have simple Serial Problem

Using the code below and entering (say) a “k” in hyperterminal it echoes back just that character in the HT window but the STDIO window “adds” a set of characters like; s = kx4�Z�_��7 (the same set of characters appears after each entry). I want eventually to collect a string of characters sent down the serial line together into a single string array

#define DINBUFSIZE 31
#define DOUTBUFSIZE 31
void main() {
int n; char s[16];
serDopen(19200);
while (1) {
if((n = serDread(s, 15, 20)) > 0) {
serDwrite(s, n);
printf("s = %s
",s);
}
}
serDclose;
}

I finally got the fix for this from tech support (there was no reply to my original). If any other novice has similar problems the fix is;

add these lines
memset(s, 0x00, sizeof(s)); // Clear data buffer
memset(str, 0x00, sizeof(str)); // these are necessary

before the serDopen(19200); line

Hope this helps

I’m not sold on that solution.

AFAICS it still has two or three potential problems.

Your problem is that serXread and serXwrite handle binary data, so serXread does not automatically null-terminate the received data. If you need it null-terminated, as you do for printf, you must terminate it yourself. memset() will simply null out the buffers at the start, but if your packets completely fill the buffer, it will remain unterminated; If your packets are of variable length, short packets will retain trailing characters from longer packets:

“a fairly long packet of data”
“a short packetcket of data”

something like s[n] = ‘\000’;
or *(s+n) = ‘\000’;
immediately before the printf will solve the latter problem. If your buffers could get 100% filled, you need at least one extra slot to hold the null.

If your packet contains a null, the printf() will stop printing at it and ignore any data that follows. In this case, printf() is simply not the right function, or you need, for example, to translate you data first to a hex string.

If your data is always text strings anyway, and they’ll always fit the buffers, you might use serXgets and serXputs instead, as they do null terminate.

FWIW, I also tend to use the sizeof() operator to get buffer sizes, that way you don’t get shot down in flames if you later change the buffer size and don’t change the, e.g., the serCread length.

G.