我想发送固定数量的字节来表示可以解析为整数值的数值



我想将一组连续字节中的多个不同整数发送到arduino,以表示后续电机控制的变量值。例如,我希望前 3 个字节能够存储一个范围从 0 到 1.000.000 的单个数字。那么我希望接下来的两个字节是一个较小的单独数字。当我使用随机二进制数运行此代码时,我没有得到任何预期值。

byte data[14];
long accel1;
long accel2;
long spd1;
long spd2;
long pos1;
long pos2;
void loop () {
if (Serial.available()){
size_t numbytes = Serial.readBytes(data, 14);
for(int i = 0;i<=14;i++){
Serial.println(data[i]);
}
pos1 = readthreebytes(data[1], data[2], data[3]);
pos2 = readthreebytes(data[4], data[5], data[6]);
spd1 = readtwobytes(data[7], data[8]);
spd2 = readtwobytes(data[9], data[10]);
accel1 = readtwobytes(data[11], data[12]);
accel2 = readtwobytes(data[13], data[14]);
}
}
long readthreebytes(byte firstbyte, byte secondbyte, byte thirdbyte){
long result = (firstbyte << 16) + (secondbyte << 8) + thirdbyte;
return result;
}
long readtwobytes(byte firstbyte, byte secondbyte){
long result = (firstbyte << 8) + secondbyte;
return result;
}

如果有人能帮助我解决这个问题,将不胜感激。

long readthreebytes(byte firstbyte, byte secondbyte, byte thirdbyte){
unsigned int result = (firstbyte << 16) + (secondbyte << 8) + thirdbyte;
return result;
}

这是行不通的。 字节的大小为 8 位。 如果你把它向左移动 16 位,无论你从什么开始,你都会得到 0。 如果你想像那样移动,请尝试将字节转换为 long。

long readthreebytes(byte firstbyte, byte secondbyte, byte thirdbyte){
unsigned int result = ((unsigned long)firstbyte << 16) + ((unsigned long)secondbyte << 8) + thirdbyte;
return result;
}

最新更新