[英]arduino read hex from serial rs232 in
i have problem with get read serial data from rs232 Tx RX我从 rs232 Tx RX 读取串行数据时遇到问题
my code is我的代码是
uint8_t cc;
char rtx[MAX_LEN] = { 0 };
int ii, lenn = 0;
Serial.print("recv (HEX): ");
Serial.println();
while (mySerial.available())
{
cc = mySerial.read();
if (cc < 0x10) Serial.print("0");
Serial.print(cc, HEX);
rtx[lenn] = cc; lenn++;
Serial.print("");
}
Serial.println();
Here i can see my outputs with out problem在这里我可以看到我的输出没有问题
output is for example例如 output
recv (HEX):
030039094C80703470326421A5713DFE01EA6B79AE8D9DBD94F523F95340217C739BCB3B75DE1D1EF09CF03D2F916AB390E92136074A41BBA4E95ACB
the problem i want to println rtx from out the while我想从外面打印 rtx 的问题
for example i have used this code例如我用过这段代码
char buffer[MAX_LEN] = { 0 };
sprintf(buffer, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",rtx[0],rtx[1],rtx[2],rtx[3],rtx[4],rtx[5],rtx[6],rtx[7],rtx[8],rtx[9],rtx[10],rtx[11],rtx[12],rtx[13],rtx[14],rtx[15],rtx[16],rtx[17],rtx[18],rtx[19],rtx[20]);
Serial.println(buffer);
it give only limited data with wrong它只给出有限的错误数据
i got this我懂了
0300FF39094FFFC807034FFF70326421A571 0300FF39094FFFC807034FFF70326421A571
the problem is add FFF in out and i can't get all rtx[21],rtx[22],rtx[23],rtx[23],rtx[24]......问题是在 out 中添加 FFF,我无法获取所有 rtx[21]、rtx[22]、rtx[23]、rtx[23]、rtx[24]......
Your buffer needs to be twice as large plus a trailing zero byte:您的缓冲区需要两倍大加上一个尾随零字节:
uint8_t buffer[MAX_LEN*2 + 1] = { 0 };
sprintf(buffer, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",rtx[0],rtx[1],rtx[2],rtx[3],rtx[4],rtx[5],rtx[6],rtx[7],rtx[8],rtx[9],rtx[10],rtx[11],rtx[12],rtx[13],rtx[14],rtx[15],rtx[16],rtx[17],rtx[18],rtx[19],rtx[20]);
Serial.println(buffer);
The values are stored in bytes, but to convert them to a hex string each value needs 2 bytes/chars.这些值以字节存储,但要将它们转换为十六进制字符串,每个值需要 2 个字节/字符。
The number of parameters do not match the format string (21 parameters, 20 in format string).参数个数与格式字符串不匹配(21 个参数,20 个格式字符串)。
While reading, you have to check for MAX_LEN to avoid buffer overflow.阅读时,您必须检查 MAX_LEN 以避免缓冲区溢出。
Here is some example code to read and display the buffer:下面是一些读取和显示缓冲区的示例代码:
#define MAX_LEN 100
uint8_t rtx[MAX_LEN] = { 0 };
ReadData();
PrintBuffer(20);
int ReadData()
{
int lenn = 0;
Serial.println("recv (HEX): ");
while (mySerial.available()) {
if (lenn >= MAX_LEN) {
Serial.println();
Serial.println("Buffer overflow");
return(-1);
}
uint8_t cc = mySerial.read();
PrintHexByte(cc);
rtx[lenn++] = cc;
}
Serial.println();
return(0);
}
void PrintBuffer(int len)
{
if (len < 0 || len > MAX_LEN)
len = MAX_LEN;
for (int i = 0; i < len; ++i) {
PrintHexByte(rtx[i]);
}
Serial.println();
}
void PrintHexByte(uint8_t cc)
{
if (cc < 0x10)
Serial.print("0");
Serial.print(cc, HEX);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.