Last active
February 17, 2019 16:04
-
-
Save shockwaves/4c272b21cc12a527f09eaaa86ea0483e to your computer and use it in GitHub Desktop.
arduino-ultrasonic-gates.ino
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Ultrasonic.h> | |
#include <Servo.h> | |
// Pins setup | |
#define RED_LED 2 // Light stop | |
#define GREEN_LED 3 // Light allow | |
#define SERVO_GATE 9 // Gate servo | |
#define TRIG 12 // Ultrasonic Trig | |
#define ECHO 13 // Ultrasonic Echo | |
Servo myservo; | |
Ultrasonic ultrasonic(TRIG, ECHO); | |
int distance; | |
unsigned long timePresence; | |
bool carPresence = false; | |
bool gatesOpened = false; | |
bool isDelayPresence; | |
int pos = 90; | |
void setup() | |
{ | |
pinMode(RED_LED, OUTPUT); | |
pinMode(GREEN_LED, OUTPUT); | |
digitalWrite(RED_LED, HIGH); | |
digitalWrite(GREEN_LED, HIGH); | |
myservo.attach(SERVO_GATE); | |
myservo.write(pos); | |
Serial.begin(9600); | |
} | |
void loop() | |
{ | |
distance = ultrasonic.read(); | |
Serial.print("Distance in CM: "); | |
Serial.println(distance); | |
if (distance < 9) | |
{ | |
if (!carPresence) | |
{ | |
carPresence = true; | |
timePresence = millis(); | |
digitalWrite(RED_LED, LOW); | |
} | |
Serial.println("Car detected"); | |
isDelayPresence = (millis() - timePresence) > 1000; | |
if (!gatesOpened && isDelayPresence) | |
{ | |
while (pos > 0) | |
{ | |
myservo.write(pos); | |
delay(15); | |
pos -= 1; | |
} | |
gatesOpened = true; | |
Serial.println("Gates opened"); | |
digitalWrite(RED_LED, HIGH); | |
digitalWrite(GREEN_LED, LOW); | |
} | |
} | |
else | |
{ | |
if (carPresence) | |
{ | |
carPresence = false; | |
timePresence = millis(); | |
digitalWrite(RED_LED, HIGH); | |
} | |
isDelayPresence = (millis() - timePresence) > 3000; | |
if (gatesOpened && isDelayPresence) | |
{ | |
digitalWrite(GREEN_LED, HIGH); | |
digitalWrite(RED_LED, LOW); | |
while (pos < 90) | |
{ | |
myservo.write(pos); | |
delay(15); | |
pos += 1; | |
} | |
gatesOpened = false; | |
Serial.println("Gates closed"); | |
digitalWrite(RED_LED, HIGH); | |
} | |
} | |
delay(200); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment