从串口数据中删除多余的字节 [英] Removing excess bytes from serial port data
问题描述
大家好,
所以我在这里实现 Ramone de Klein 制作的精彩系列课程:
C ++串行库 [ ^ ]
在他对Read函数的定义中,他将传入的字节写入一个大小为100的数组。问题是当我发送一个数据包时,我知道它的数量小于100,它与垃圾捆绑在一起作为剩余的字节。
我要过滤掉这个。
任何建议如:接下来我可以尝试一下吗?
我尝试过:
1.将传入的数据存储到CString中,但该函数将缓冲区变量定义为void * buffer。因此CString不起作用。
2.根据接收的字节数动态声明缓冲区变量,但该函数不接受不确定大小的数组。
Hi guys,
So I am implementing the brilliant serial class made by Ramone de Klein here:
Serial library for C++[^]
In his definition of the Read function, he writes the incoming bytes into an array of size 100. The problem is when I send a packet of data whose size I know to be less than 100, it comes bundled with garbage as the remaining bytes.
I want to filter this out.
Any suggestions as to what I could try next?
What I have tried:
1. Store the incoming data into a CString, but the function defines the buffer variable as void* buffer. So CString doesn't work.
2. Dynamically declare the buffer variable based on the number of bytes received, but the function does not accept an array of indeterminate size.
推荐答案
只是不要使用额外的字节。你通常知道收到了多少字节。
分配一个足够大的char *
缓冲区数据的最大长度(对于空终止符,可选加一个字节)。
如果您知道数据是可打印字符并且您想要创建字符串,那么必须指定长度或在缓冲区附加一个空字节。
将数据复制到CString
你可以使用
Just don't use the additional bytes. You usually know how many bytes has been received.
Allocate achar*
buffer that is large enough to hold the maximum length of data (optionally plus one byte for a null terminator).
If you know that the data are printable characters and you want to create a string, you have to specify the length or append a null byte to the buffer.
To copy the data into aCString
you can use
/* Use the constructor for char* because data are usually ASCII. */
/* Note that this converts to Unicode for Unicode builds. */
CString str(buffer, dwRead);
/* Using a CStringA and setString(): */
CStringA strA;
strA.SetString(buffer, dwRead);
或者在缓冲区附加一个空字节:
Or append a null byte to the buffer:
/* Check for buffer overrun. */
/* RX_BUF_SIZE is the size of the allocated buffer. */
ASSERT(dwRead < RX_BUF_SIZE);
buffer[dwRead] = 0;
CString str(buffer);
这篇关于从串口数据中删除多余的字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!