我想将一组连续字节中的多个不同整数发送到 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;
}
关于c++ - 我想发送固定数量的字节来表示可以解析为整数值的数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57381431/