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