简体   繁体   English

如何使用 Arduino 使伺服按下按钮?

[英]How to make a servo push a button with Arduino?


I'm trying to replicate the toy "uselsess box" with Arduino but in a different version. 我正在尝试使用 Arduino 复制玩具“无用的盒子”,但版本不同。
I have a button, a led and a servo motor. 我有一个按钮、一个 LED 和一个伺服电机。
When I click the button the led lights up and after 2 seconds I want the servo motor to rotate and push that button again to turn off the led. 当我单击按钮时,LED 亮起,2 秒后,我希望伺服电机旋转并再次按下该按钮以关闭 LED。
The problem is that when I press the button the led lights up and at the same time the servo motor moves, in this way when it clicks the button the led does not turn off. 问题是当我按下按钮时,LED灯亮,同时伺服电机移动,这样当它点击按钮时,LED不会关闭。
Here's the code: 这是代码:
 #include <Servo.h> int servoPin = 3; Servo Servo1; const int button = 7; const int led = 8; int ledState = 0; void setup() { Servo1.attach(servoPin); pinMode(led, OUTPUT); pinMode(button, INPUT); } void loop() { if (digitalRead(button) == HIGH) { if (ledState == 0) { ledState = 1; digitalWrite(led, HIGH); delay(2000); Servo1.write(0); delay(1000); Servo1.write(100); delay(1000); } } else { ledState = 0; digitalWrite(led, LOW); Servo1.write(0); } }

did you try this?你试过这个吗?

bool check = true;
void loop() {
 if (digitalRead(button) == HIGH && check) {
   check = false;
   if (ledState == 0) {
     ledState = 1;
     digitalWrite(led, HIGH);

     delay(2000);
     Servo1.write(0);
     delay(1000);
     Servo1.write(100);
     delay(1000);
   }
   else {
     ledState = 0;
     digitalWrite(led, LOW);
     Servo1.write(0);
   }
 }
if (digitalRead(button) == LOW) {
   check = true;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM