串行读取更改输入并且不读取整行

serial read changes input & doesn't read whole line

使用 Arduino Uno 和 Arduino IDE 无法正确读取通过串行发送的大字符串。当键入的命令太长时,返回的不是全部数据,有时甚至是随机数。

99,3,0,1,0,0,0 结果正确(不确定为什么有结尾 , tho): receivedValues are: 99,3,0,1,0,0,0,

99,3,0,0,0,0,0 结果正确:receivedValues are: 99,3,0,0,0,0,0,

哪里开始出错了:

99,3,0,100,200,300,400 结果:receivedValues are: 99,3,0,100,200,44,144,

99,123456789 结果:receivedValues are: 99,21,0,1,200,200,244,

99,3,0,1,200,200,2000 结果:receivedValues are: 99,3,0,1,200,200,208,

这是我的相关代码部分:

uint8_t receivedValues[7] = {0, 0, 0, 0, 0, 0, 0};

#define HEADER 0 // 99
#define CMD   1 // LICHT (2)   || GEUR (3)
#define DATA0 2 // KLEUR INDEX || GEUR INDEX
#define DATA1 3 // H           || ON / OFF
#define DATA2 4 // S
#define DATA3 5 // V
#define DATA4 6 // BlendTime

#define CHECK 99

#define ON 1
#define OFF 0

bool messageReceived = false;
bool startBlending = false;

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  ParseSerial();
  if (messageReceived)
  {
    printMessage();
    // CheckCommand();
    messageReceived = false;
  }
}


void ParseSerial()
{
  int serialIndex = 0;
  if (Serial.available() > 8)
  {
    while (0 < Serial.available())
    {
      String bufferString;
      int bufferInt;

      bufferString = Serial.readStringUntil(',');
      bufferInt = bufferString.toInt();
      receivedValues[serialIndex] = bufferInt;

      serialIndex++;
    }
    if (receivedValues[HEADER] == CHECK)
    {
      Serial.print("receivedValues[0]: ");
      Serial.println(receivedValues[0]);
      messageReceived = true;
    }
    if (receivedValues[HEADER] != CHECK)
    {
      Serial.println("not a good package");
    }
    Serial.flush();
  }
  else
  {
    Serial.flush();
  }
}

void printMessage()
{
  Serial.print("receivedValues are: ");
  for (int i = 0; i < 7; i++)
  {
    Serial.print(receivedValues[i]);
    Serial.print(",");
  }
  Serial.println();
}

如果消息的 header 不是以 99 开头,它将写入 not a good package。值得注意的是,当我在开始时输入带有 99 的命令时,大多数时候它会写两次 not a good package

receivedValues 声明为 uint8_t receivedValues[7]uint8_t 的最大值为 255。如果您尝试存储更大的数字,它将被截断。

如果要存储更大的数字,则需要为数组选择更宽的整数类型,例如

uint32_t receivedValues[7] = {0, 0, 0, 0, 0, 0, 0};

最多可以达到 UINT32_MAX,也就是 0xFFFFFFFF (4294967295)

我找到了解决这个问题的方法。改变 uint8_t 不是答案。

A byte of 8 binary bits can represent 28 = 256 numbers: 0 - 255. The serial connection sends data byte by byte, so if you want to send a number larger than 255, you'll have to send multiple bytes

Link 来源: https://forum.arduino.cc/index.php?topic=492055.0

我最终发送了一个小于 255 的数字(分钟),然后在 Arduino 代码中再次乘以它(到秒)。