问题描述
嗨,我开始研究 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() {
}
解决方法
需要解决的几点:
- 您的主要代码应该在
loop()
内运行。 - 通过使用一些简单的逻辑,您可以在循环内只运行一次打印
- 这不会打印数组中的元素。为什么在
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
}
}