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

时间:2019-06-15 07:45:27

标签: arduino esp8266 arduino-ide nodemcu

我已经将NodeMCU与Pir传感器和伺服电动机连接起来,并且该代码用于在检测到运动时旋转伺服器,因此我已经void setup()对其进行了旋转,并且可以正常工作,但是稍后在{{ 1}}无效

void loop()

1 个答案:

答案 0 :(得分:0)

您只需在检测到运动时就切换伺服器,即可创建一个功能  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);
    }
}