首页 > 解决方案 > 如何在不知道 Arduino 大小的情况下创建数组并在其中存储值

问题描述

我正在尝试为从另一个 Arduino(发射器)接收十六进制值的接收器编写 Arduino 代码,然后我想检查这些值并将它们存储在我不知道其大小的新数组中,而发射器发送值接收器将存储他们。

值成功到达接收器,但我不知道如何将它们存储在新数组中。

我的接收器代码是这样的:

for (i = 0; i < len; i++)
{
 if (receivedValue[i]==0x60)
          {
    //digitalWrite(LED1,LOW); 
    // store receivedValue[i] in the new array
          }
          else
          {
            if(receivedValue[i]==0x61)
            {
            //digitalWrite(LED3,LOW); 
             // store receivedValue[i] in the new array
            }

            if (receivedValue[i]==0x62)
            {
            //digitalWrite(LED4,LOW); 
              // store receivedValue[i] in the new array
          }

          // any other receivedValue[i] dont do anything
        }
    }

LED 可以按我的意愿成功工作,但是如何将它们存储在数组中?

标签: c++arduino

解决方案


提出了两种方法:

  1. 预定义固定大小的数组

    #define MAX_ITENS 50       // The size of buffer
    uint8_t buffer[MAX_ITENS]; // The Buffer
    uint8_t posBuffer = 0;     // Pointer to actual position
    
    loop() {
        .... 
        // Add data to buffer
        posBuffer++;
    
        if (posBuffer == MAX_ITENS) {
            // Buffer overflow - You can set position to 0 
            // or give some error
        } else {
            buffer[posBuffer] = data; // Save the data
        }
    }
    
  2. 使用我喜欢的动态数组


推荐阅读