Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Serial port 检查字节数组时出错_Serial Port_Arduino_Error Checking - Fatal编程技术网

Serial port 检查字节数组时出错

Serial port 检查字节数组时出错,serial-port,arduino,error-checking,Serial Port,Arduino,Error Checking,检查字节数组中的数据是否正确的最佳方法是什么 我通过串行连接发送一个字节数组,例如,字节1、字节2、字节3、字节4和errorCheckByte,我希望在收到数据时检查数据是否正确 要确定连接两端的前四个字节是否相同,最好的数学运算是什么?我应该把它们加在一起吗 例如,但实际上并不寻找特定于语言的示例,但这与Java和Arduino有关: byte byte1 = 5; byte byte2 = 10; byte byte3 = 34; byte byte4 = 122; byte error

检查字节数组中的数据是否正确的最佳方法是什么

我通过串行连接发送一个字节数组,例如,字节1、字节2、字节3、字节4和errorCheckByte,我希望在收到数据时检查数据是否正确

要确定连接两端的前四个字节是否相同,最好的数学运算是什么?我应该把它们加在一起吗

例如,但实际上并不寻找特定于语言的示例,但这与Java和Arduino有关:

byte byte1 = 5;
byte byte2 = 10;
byte byte3 = 34;
byte byte4 = 122;

byte errorCheckByte = createErrorByte(byte1, byte2, byte3, byte4);

byte myArray[] = {byte1, byte2, byte3, byte4, errorCheckByte}

byte createErrorByte(byte byte1,byte byte2, byte byte3, byte byte4)
{return (byte1 + byte2 + byte3 + byte4);}
发送后,我也许可以使用以下内容进行检查

// Sum bytes received
byte sumBytes = 0;
for (int x = 0; x < 3 ; x++) {sumBytes += myArray[x]}

if (myArray[4] == sumBytes) { // Print message received}
else {
    // Discard data
}
//接收的字节总数
字节sumBytes=0;
对于(intx=0;x<3;x++){sumBytes+=myArray[x]}
if(myArray[4]==sumBytes){//Print message received}
否则{
//丢弃数据
}

是否有更好但简单的错误检查算法?

您正在寻找的是错误检查的概念。对于少量数据,该方法是一种常见的选择,例如CRC32。

是否可以给出一个示例函数,从4字节的数据中计算8位的CRC,我读过这些文章,虽然有用,但我的数学能力还不足以自己计算。@Zac是的,这绝对是可能的。为什么不谷歌“CRC实现C”?校验和可能比没有测试要好,但CRC要好得多。简单求和不会检测交换的字节,但CRC会检测。