为什么串行接收到的消息会被存储在Char Array中?

问题描述 投票:0回答:1

我的Arduino代码在接收到来自串口的消息后,出现了一个问题。

这个问题是,当通过串口接收到 "START "消息后,Arduino继续执行了函数 startSequence() 使用两个随机数,从一个二维矩阵中获取8个值,并将这些值存储在一个char数组中。

这里的问题是,尽管这个char数组已经被声明为8个大小,但 "START "信息会被附加到这个char数组的末尾,它根本不应该这样做,这个信息应该在 handleReceivedMessage(char *msg). 我的代码。

#include <Keypad.h>

const byte ROWS = 4;
const byte COLS = 4;

char hexaKeys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
char newSecretCode[8];
char introducedSecretCode[8];

byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};

int secretCodeIndex = 0;

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

void setup() {
  Serial.begin(9600);
  delay(2000);  //Delay to allow initializations on Raspberry side
  Serial.println("COM:SETUP;INT_NAME:Keypad Puzzle;BAUD:9600");
  randomSeed(analogRead(0));
}

void loop() {
  if (Serial.available()) {
    processSerialMessage();
  }
  char customKey = customKeypad.getKey();
  if (customKey) {
    if (secretCodeIndex < 8) {
      introducedSecretCode[secretCodeIndex] = customKey;
      secretCodeIndex += 1;
    } else {
      secretCodeIndex = 0;
    }
  }
}

void processSerialMessage() {
  const int BUFF_SIZE = 32; // make it big enough to hold your longest command
  static char buffer[BUFF_SIZE + 1]; // +1 allows space for the null terminator
  static int length = 0; // number of characters currently in the buffer

  char c = Serial.read();
  if ((c == '\r') || (c == '\n')) {
    // end-of-line received
    if (length > 0) {
      handleReceivedMessage(buffer);
    }
    length = 0;
  }
  else {
    if (length < BUFF_SIZE) {
      buffer[length++] = c; // append the received character to the array
      buffer[length] = 0; // append the null terminator
    } else {
      // buffer full - discard the received character
    }
  }
}

void handleReceivedMessage(char *msg) {
  if (strcmp(msg, "START") == 0) {
    startSequence();
    Serial.println("COM:START_ACK;MSG:Set new code to " + String(newSecretCode));
  }else {
    // etc
  }
}

void startSequence() {
  for (int i = 0; i < 8; i++) {
    newSecretCode[i] = hexaKeys[random(0,ROWS)][random(0,COLS)];
  }
}

我看了一遍又一遍的代码 但我不明白为什么我通过串行接收到的信息 会被添加到一个大小只有8的数组的末尾。下面是一些输出的例子,除了字符串末尾的 "START "消息,其他都是正确的。

Output generated by sending "START" command through serial

提前感谢大家的帮助,如果错误很明显,我表示歉意,但我把这段代码看了一遍又一遍,似乎找不到。

c arrays arduino serial-port
1个回答
1
投票

如果你希望newSecretCode作为一个字符串,你需要null终止它。 但最好不要使用String类来转换你不需要转换的东西。 这样打印吧。

void handleReceivedMessage(char *msg) {
  if (strcmp(msg, "START") == 0) {
    startSequence();
    Serial.println("COM:START_ACK;MSG:Set new code to " );
    for (int i=0; i<8; i++){
      Serial.print(newSecretCode[i]);
    }
  }else {
    // etc
  }
}

串行数据一个字节一个字节地传出去。 另一端的接收器只是看到一个连续的字节流。 它不知道你是用一条打印语句做的,在String上浪费了一大堆资源,还是为每个字符单独打印语句做的。

© www.soinside.com 2019 - 2024. All rights reserved.