我已将NodeMCU与Pir Sensor和Servo Motor连接,并且该代码用于在检测到运动时旋转伺服器,因此我放置了一次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 - I've connected servo and PIR with NodeMCU and Servo isn't工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56608441/

10-09 20:31