Reading from serial prints garbage
I'm trying to configure a serial communication between a dsp and my computer.
The dsp sends the value of a 16-bit counter which increments each time it is sent. So it's just counting...
Here is what I get on my computer :
3335 3336 3337 3338 36388 46920 16372 46919 3339 3340 3341 3342 36388 46920 16372 46919 3343 3344 4621 3341 36388 46920 ...
So we can see the counter which is interrupted by those 4 values that comes out of nowhere...
My program is configured with
fd = open(device.c_str(), O_RDWR | O_NOCTTY | O_NDELAY);
fcntl(fd, F_SETFL, FNDELAY);
termios options;
tcgetattr(fd开发者_高级运维, &options);
cfsetispeed(&options, B4800);
cfsetospeed(&options, B4800);
options.c_cflag |= (CLOCAL | CREAD | CS8);
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_iflag |= (IXON | IXOFF | IXANY);
tcsetattr(fd, TCSANOW, &options);
The DSP sends 4800/8N1.
Any idea ?
I strongly suspect those are being sent by the DSP, the serial port drivers are pretty well debugged by now.
Other possibilities are that you're reading the serial port from multiple threads at once (maybe in the same process, maybe not). Open the port exclusively to make sure that isn't your problem.
Or, you could be reading the expected values from the serial port, and adding garbage in some buffering/queuing inside your program. Possibly you're getting partial reads (due to receive timeout).
Remember that the return value of read
is measured in bytes, not 16-bit values. If you were receiving 8 bytes and then printing 8 shorts, you would see this sort of behavior. (However, the problems with the last two values, 4621 3341, in the "sequence" can't be explained this way.) Based on comments from the OP, this appears to be the exact cause of the problem
In no case is this problem attributable to serial port configuration.
Lol I'm so sorry, the cause of the problem was elsewhere, I was doing
unsigned short buffer[4];
n = read(..., buffer, ...); // n in bytes !
Then
for (int i = 0; i < n; ++i)
dump << buffer[i] << std::endl; // index in 16-bits !
So I was always reading my buffer of 4 items + 4 values (from the stack I guess)...
Thanks for your answers though...
精彩评论