如何解决对于循环 Arduino,访问数组中的所有位置
嗨,我开始研究 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
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。