英文:
Exiting loop in Arduino after doing an operation for specific number of times
问题
我可以帮你修改Arduino中的void loop
函数,使其在打开和关闭灯/电磁阀30次后退出循环。修改后的代码如下:
int relay = 8;
int count = 0;
void setup() {
// put your setup code here, to run once:
pinMode(relay, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
if (count < 30) {
digitalWrite(relay, HIGH);
delay(5000);
digitalWrite(relay, LOW);
delay(200);
count++;
} else {
// Exit the loop
while (true) {
// Do nothing or add your desired code here
}
}
}
这样修改后,当循环执行了30次后,程序将进入一个无限循环,你可以在其中添加你想要的代码,或者保持空白。这样就实现了在打开和关闭灯/电磁阀30次后退出循环的功能。希望对你有帮助!
英文:
I want to turn on light/solenoid valve on and off 30 times only, and after that I want to exit the loop. How can I modify the void loop in Arduino? My program is given below. Thanks for your help.
int relay = 8;
void setup() {
// put your setup code here, to run once:
pinMode(relay, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(relay, HIGH);
delay(5000);
digitalWrite(relay, LOW);
delay(200);
}
答案1
得分: 1
只需使用一个for循环。我不会帮你做作业,但你可以查看这个网站:https://www.geeksforgeeks.org/python-for-loops/
英文:
Just use a for loop. I won't do your homework for you, but check this site. https://www.geeksforgeeks.org/python-for-loops/
答案2
得分: 0
这个想法是将你的代码从loop
函数中移出(该函数在循环中被无限调用),而是在setup
函数中调用你的代码一次(该函数只被调用一次)。
然后,你可以使用一个for循环
来重复执行你的代码n次(在这个例子中是30次)。
这里有一个示例(显然可以进行重构),但应该能够演示你想要实现的目标:
int relay = 8;
void setup() {
// 在这里放置你的设置代码,只运行一次:
pinMode(relay, OUTPUT);
// 切换30次
for (int i = 0; i < 30; i++) {
digitalWrite(relay, HIGH);
delay(5000);
digitalWrite(relay, LOW);
delay(200);
}
}
void loop() {
// 在这里放置你的主要代码,重复运行:
}
英文:
The idea is to move your code out of the loop
function (which is called forever in a loop), and instead to call your code once in the setup
function (which is called once).
You then can wrap your code in a for loop
to have it repeat n times (in this case 30).
Here is an example (which obviously can be refactored), but should demonstrate what you are trying to accomplish:
int relay = 8;
void setup() {
// put your setup code here, to run once:
pinMode(relay, OUTPUT);
// toggle 30 times
for (int i = 0; i < 30; i++) {
digitalWrite(relay, HIGH);
delay(5000);
digitalWrite(relay, LOW);
delay(200);
}
}
void loop() {
// put your main code here, to run repeatedly:
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论