Add logic to open the Barrier (Servo) when de distance sensor is activated
This commit is contained in:
parent
004f70da0b
commit
db788f5889
44
code/Barrier.cpp
Normal file
44
code/Barrier.cpp
Normal file
@ -0,0 +1,44 @@
|
||||
#include <Servo.h>
|
||||
|
||||
enum BarrierState {OPEN, CLOSED};
|
||||
|
||||
class Barrier {
|
||||
|
||||
private:
|
||||
Servo servo;
|
||||
int pin;
|
||||
BarrierState state = CLOSED;
|
||||
|
||||
public:
|
||||
|
||||
int open_time_seconds;
|
||||
|
||||
Barrier(int pin, int open_time_seconds = 3){
|
||||
this->pin = pin;
|
||||
this->close();
|
||||
this->open_time_seconds = open_time_seconds;
|
||||
}
|
||||
|
||||
void configure_pins(){
|
||||
this->servo.attach(pin);
|
||||
}
|
||||
|
||||
void open(){
|
||||
this->state = OPEN;
|
||||
this->servo.write(0);
|
||||
}
|
||||
|
||||
void close(){
|
||||
this->state = CLOSED;
|
||||
this->servo.write(90);
|
||||
}
|
||||
|
||||
bool is_open() const {
|
||||
return this->state == OPEN;
|
||||
}
|
||||
|
||||
bool is_closed() const {
|
||||
return this->state == CLOSED;
|
||||
}
|
||||
|
||||
};
|
||||
@ -1,19 +1,34 @@
|
||||
#include <Servo.h>
|
||||
#include "Barrier.cpp";
|
||||
#include "DistSensor.cpp";
|
||||
|
||||
#define ULTRASONIC_SENSOR_PIN_TRIG 11
|
||||
#define ULTRASONIC_SENSOR_PIN_ECHO 12
|
||||
#define SERVO_PIN 10
|
||||
|
||||
unsigned long previous_time = 0;
|
||||
|
||||
DistSensor dist_sensor = DistSensor(ULTRASONIC_SENSOR_PIN_TRIG, ULTRASONIC_SENSOR_PIN_ECHO, 25.0);
|
||||
Barrier barrier = Barrier(SERVO_PIN, 3);
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
dist_sensor.configure_pins();
|
||||
barrier.configure_pins();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
|
||||
unsigned long current_time = millis();
|
||||
|
||||
if (dist_sensor.is_in_range()){
|
||||
previous_time = current_time;
|
||||
if(barrier.is_closed()){
|
||||
barrier.open();
|
||||
}
|
||||
} else if (!dist_sensor.is_in_range() && barrier.is_open()){
|
||||
if (current_time - previous_time >= barrier.open_time_seconds * 1000){
|
||||
barrier.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user