gpt4 book ai didi

arduino - 我已将伺服和 PIR 与 NodeMCU 连接,但伺服无法正常工作

转载 作者:行者123 更新时间:2023-12-02 04:23:58 24 4
gpt4 key购买 nike

我已经将 NodeMCU 与 Pir 传感器和伺服电机连接起来,代码用于在检测到运动时旋转伺服系统,因此我一旦 void setup() 就将其旋转。这工作正常,但后来在 void loop()它不起作用

#include<Servo.h>
Servo servo;
int pirPin = 2;
int state = LOW;
void setup() {
Serial.begin(115200);
servo.attach(13);
servo.write(30);
pinMode(pirPin, INPUT);
}

void loop(){
if(digitalRead(pirPin) == HIGH)
{
if (state == LOW) {
Serial.println("Motion detected");
int angle;
servo.write(90);
delay(1000);
state = HIGH;
}

} else {

if (state == HIGH){
Serial.println("Motion not detected");
servo.write(90);
state = LOW;
}

}
}

最佳答案

您只需要在检测到运动时切换伺服。创建函数
喜欢 servo_toggle_state改变伺服状态。像这样的东西:

#include <Servo.h>
Servo servo;
int pirPin = 2;
bool state = false;

void servo_toggle_state()
{
if (state)
servo.write(90);
else
servo.write(0);
state = !state;
}

void setup()
{
Serial.begin(115200);
servo.attach(13);
servo.write(30);
pinMode(pirPin, INPUT);
//set servo at 0 on start
servo.write(0);
}

void loop()
{
if (digitalRead(pirPin) == HIGH)
{
Serial.println("Motion detected");
servo_toggle_state();
//wait while motion is still detected
while(digitalRead(pirPin));
delay(1000);
}
}

关于arduino - 我已将伺服和 PIR 与 NodeMCU 连接,但伺服无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56608441/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com