Skip to content

Instantly share code, notes, and snippets.

@whatsim
Last active July 2, 2023 02:40
Show Gist options
  • Save whatsim/96ea981a937cef1079e761fc42a233b6 to your computer and use it in GitHub Desktop.
Save whatsim/96ea981a937cef1079e761fc42a233b6 to your computer and use it in GitHub Desktop.
/* Sensor Triggers Servo*/
// Define connection pins:
#define pirPin 2
#define ledPin 13
#include <Servo.h>
Servo myservo; //Create servo object to control a servo
bool motionState = false; // We start with no motion detected.
unsigned long lastActivation = 0;
unsigned long risingDebounceTime = 2000;
unsigned long fallingDebounceTime = 5000;
int targetPos = 0;
int currentPos = 0;
int potpin = A1;
int potpin2 = A0;
void setup() {
// Configure the pins as input or output:
pinMode(ledPin, OUTPUT);
pinMode(pirPin, INPUT);
// Begin serial communication at a baud rate of 9600:
Serial.begin(9600);
// attach servo connected to pin 9 to the servo object
myservo.attach(9);
}
void loop() {
speed = analogRead(potpin);
speed = map(speed, 0, 1023, 100, 20);
angle = analogRead(potpin2);
angle = map(angle, 0, 1023, 45, 180);
int val = digitalRead(pirPin);
unsigned long now = millis();
// are we reading motion right now
if (val == HIGH) {
// was there no motion last frame?
if (motionState == false && now > lastActivation + risingDebounceTime) {
// if so, this is new motion and we do all the things
digitalWrite(ledPin, HIGH);
Serial.println("Motion detected!");
targetPos = angle;
lastActivation = now;
motionState = true;
}
} else { // If no motion is detected (pirPin = LOW), do the following:
// was there motion last frame?
if (motionState == true && now > lastActivation + fallingDebounceTime) {
// if yes, motion just ended, so lets do our clean up
digitalWrite(ledPin, LOW);
Serial.println("Motion ended!");
targetPos = 0;
lastActivation = now;
motionState = false;
}
}
if (targetPos < currentPos) {
currentPos --;
myservo.write(currentPos);
delay(speed);
} else if (targetPos > currentPos) {
currentPos ++;
myservo.write(currentPos);
delay(speed);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment