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

标签 c++ serialization arduino

我想将一组连续字节中的多个不同整数发送到 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/

相关文章:

C++ 程序在执行 std::string 分配时总是崩溃

java - Tinkerpop 注册自定义类 kryo

c++ - 全局静态 bool 指针使用 pthread 导致段错误

c++ - 是否有一种很好的通用方法可以在 ruby​​ 中包装 swig 生成的类?

c# - 通过网络发送自定义结构 - SerializationException

c++ - 在我的 Arduino 库中使用外部库

arduino - 在 Godot 中接收 Arduino 输入

c++ - 我应该使用什么变量类型来存储 Arduino 引脚状态?

c++ - 读取描述符(ioctl、fcntl)

asp.net - 如何获取JsonResult对象作为字符串,以便可以对其进行修改?