arduino - 将按钮合并到伺服回路中
问题描述
我非常新,所以请和我一起裸露。我试图通过内部计时器和按钮来控制伺服。基本上,伺服系统每 24 小时左右会打开一扇门 6 秒,或者如果您按下按钮,请在此处输入图像描述
计时器的循环有效,但按钮无效。但是,如果我只是上传按钮代码,它工作正常。请帮忙!如果在按住按钮时伺服可以达到 180 并在释放时返回 0,那就更好了。
这是我的代码。请告诉我我在哪里搞砸了!
#include <Servo.h>
Servo myservo;
const int BUTTON_PIN = 8;
const int SERVO_PIN = 9;
int angle = 0; // the current angle of servo motor
int lastButtonState; // the previous state of button
int currentButtonState; // the current state of button
void setup(){
myservo.attach(SERVO_PIN);
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
myservo.write(angle);
currentButtonState = digitalRead(BUTTON_PIN);
}
void loop(){
myservo.write(0);// move servos to center position -> 90°
delay(18000);
myservo.write(180);// move servos to center position -> 120°
delay (6000);
lastButtonState = currentButtonState; // save the last state
currentButtonState = digitalRead(BUTTON_PIN); // read new state
if(lastButtonState == HIGH && currentButtonState == LOW) {
Serial.println("The button is pressed");
// change angle of servo motor
if(angle == 180)
angle = 0;
else
if(angle == 0)
angle = 180;
// control servo motor arccoding to the angle
myservo.write(angle);
}
}
解决方案
根据您的图片,您的引脚应该是 7 和 9。基本上,您的代码的唯一问题是,如果您还想监视某些东西(您的按钮),则不能使用延迟。因此,您可以使用所谓的看门狗计时器,在这种情况下,您基本上可以根据系统时钟经常发生某些事情,但是当它没有发生时,您也可以继续做其他事情。
比较 arduino 示例草图文件夹中的闪烁和无延迟闪烁示例可能有助于进一步解释这个概念。
#include <Servo.h>
Servo myservo;
const int BUTTON_PIN = 7;
const int SERVO_PIN = 9;
unsigned long dayTimer_ms = 0;
unsigned long autoOpenDelay_ms = 86400000;
int angle = 0;
void setup(){
myservo.attach(SERVO_PIN);
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
myservo.write(0);
}
void loop() {
if(millis() - dayTimer_ms > autoOpenDelay_ms )
{
dayTimer_ms = millis();
myservo.write(180); //(open?)
delay(6000);
myservo.write(0);
}
if(millis()<dayTimer_ms)//overflow handling (in case this runs for more than 50 days straight)
{
dayTimer_ms = millis();
}
if (!digitalRead(BUTTON_PIN) && angle != 180)
{
angle = 180;
myservo.write(angle);
}
if (digitalRead(BUTTON_PIN) && angle != 0)
{
angle = 0;
myservo.write(angle);
}
}
推荐阅读
- c++ - 服务器套接字在后台运行时无法正常工作
- python - 如何使用 postgres 在 django 中获取数组字段数据
- python - 如何使用 django 和 GeoIP2 保存和显示用户 IP 和位置
- elasticsearch - elasticsearch中多个字段的聚合
- arrays - 具有特定类型的对象数组
- c - A Little C 程序中的一些问题
- scala - spark scala maven 错误:SparkConf 没有构造函数
- node.js - 在 Hyperledger Fabric NodeJS 智能合约中实例化链码后,如何防止调用“init”函数?
- angular - ng v 命令给出错误:“路径”参数必须是字符串、缓冲区或 URL 类型之一。接收到的类型对象'
- c# - 在碰撞的游戏对象中激活脚本