【问题标题】:For loop Arduino, access all positions in array对于循环Arduino,访问数组中的所有位置
【发布时间】:2021-04-27 19:28:27
【问题描述】:

您好,我开始学习 Arduino,我需要一些帮助。

我写了这个循环,但是当我去看它的串行监视器时,它一直在无休止地重复。

如何让循环遍历这个数组并在遍历完所有位置后停止?

int x1[4];
    
void setup() {
  x1[0] = 0;
  x1[1] = 0;
  x1[2] = 1;
  x1[3] = 1;
      
  Serial.begin(9600); 

  for (byte i = 0; i < sizeof(x1); i++) {
    Serial.println(".." + sizeof(x1));
  }
}
    
void loop() {
}

【问题讨论】:

    标签: arduino arduino-uno arduino-c++


    【解决方案1】:

    几个要点:

    1. 您的主代码应该在loop() 内运行。
    2. 通过使用一些简单的逻辑,您可以在循环内只运行一次打印
    3. 这不会打印数组中的元素。为什么在 Serial.println 函数中使用 sizeof(x1) 作为参数?
    for (byte i = 0; i < sizeof(x1); i++) 
    {
            Serial.println(".." + sizeof(x1));
    }
    

    这是一个想法:

    #define ELEMENTS 4
    
    int x1[4];
    
    bool printDone;    // Boolean flag for printing once
    
    // Setup() should only be used for initializations
    
    void setup(){
    
        // Always start the serial port first
        Serial.begin(9600);
        
        // Fill your array --> consider using a loop, if possible
        x1[0] = 0;
        x1[1] = 0;
        x1[2] = 1;
        x1[3] = 1;
        
        // Initialize your flag
        printDone = false;
    }
    
    // Main functionalities from your code go inside the loop()
    
    void loop(){
        
        if (printDone == false){
    
            for(byte i = 0; i < ELEMENTS; i++){
                Serial.println(x1[i]);
            }
    
            printDone = true;    // When you are done, raise the flag
        
        }
    
     }
    

    【讨论】:

    • 我使用 sizeof no 来查看数组的大小。谢谢你告诉我我应该怎么写。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多