Hi there, I'm looking for some help with a program I'm trying to create.
I'm trying to set up a program to have my servo motor run for 5 seconds once my proximity sensor senses something at or closer than 100cm. Once the proximity sensor condition has been met, I want my MovePlayServo() function to activate for 5 seconds and stay active for the whole 5 seconds regardless of the sensor condition during the 5 second interval.
So the object can move out of the way after it triggers the sensor and the motor will still run for the full 5 seconds. After the 5 seconds, if the proximity sensor no longer senses the object the servo will not run otherwise it will run for another 5 second interval. Clearly I am going to need an if statement and some way to track time using millis(), but not really sure how to implement this cohesively.
Below is the program I have so far, I'm stuck at the loop section. Any help is much appreciated, thank you!
#include<Servo.h>
Servo PlayServo;
Servo TreatServo;
int PlayServoPosition;
int TreatServoPosition;
const int Trig = 13; // Proximity sensor trigger pin mapped to input 13
const int Echo = 12; // Proximity sensor echno pin mapped to input 12
int Duration;
int Distance;
unsigned long CurrentTime = millis();
bool PlayServoRunning;
void setup()
{
Serial.begin(9600); // Begin serial monitor
pinMode(Trig,OUTPUT); // Proximity sensor trigger pin mapped as output
pinMode(Echo, INPUT); // Proximity sensor echno pin mapped as input
}
void loop()
{
if (Distance <= 100)
}
int MovePlayServo(){
PlayServoRunning = true;
PlayServo.attach(5); // Attach PlayServo to input 5
PlayServoPosition=random(0,180);
PlayServo.write(PlayServoPosition);
Serial.print(PlayServoPosition);
Serial.println(" degrees");
delay(1000);
}
int MoveTreatServo(){
TreatServo.attach(6); // Attach PlayServo to input 5
TreatServo.write(60);
delay(1000);
TreatServo.write(0);
Serial.print(TreatServoPosition);
Serial.println(" degrees");
}
int ReadDistance(){
digitalWrite(Trig, HIGH);
delay(1);
digitalWrite(Trig, LOW);
Duration = pulseIn(Echo, HIGH);
Distance = Duration / 58.2;
Serial.print(Distance);
Serial.println(" cm");
delay(1000);
}