diff --git a/code/Barrier.cpp b/code/Barrier.cpp new file mode 100644 index 0000000..4be3e2a --- /dev/null +++ b/code/Barrier.cpp @@ -0,0 +1,44 @@ +#include + +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; + } + +}; diff --git a/code/code.ino b/code/code.ino index d408c01..666c987 100644 --- a/code/code.ino +++ b/code/code.ino @@ -1,20 +1,35 @@ -#include +#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() { - - if (dist_sensor.is_in_range()) { + 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(); + } + } }