Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Servo.h>
- #define echoPin 2
- #define trigPin 3
- #define servoPin 9
- #define buzzerPin 10
- #define ledPin 11
- Servo myservo;
- long duration;
- int distance;
- int flag = 0;
- //----------------------------------
- int alertTimes = 3;
- int alertDistance = 20; // 20 CM
- //----------------------------------
- void setup() {
- Serial.begin(9600);
- Serial.println("Serial COM Test");
- pinMode(buzzerPin, OUTPUT);
- pinMode(ledPin, OUTPUT);
- pinMode(trigPin, OUTPUT);
- pinMode(echoPin, INPUT);
- myservo.attach(servoPin);
- myservo.write(0);
- digitalWrite(ledPin, 0);
- digitalWrite(buzzerPin, 0);
- }
- void loop() {
- US();
- if (distance < alertDistance && flag == 0) {
- myservo.write(90);
- alert();
- flag = 1;
- }
- delay(50);
- }
- void US() {
- digitalWrite(trigPin, LOW);
- delayMicroseconds(2);
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- duration = pulseIn(echoPin, HIGH);
- distance = duration * 0.034 / 2;
- Serial.print("Distance: ");
- Serial.print(distance);
- Serial.println(" cm");
- }
- void alert() {
- for (int i = 0; i < alertTimes; i++) {
- digitalWrite(ledPin, 1);
- digitalWrite(buzzerPin, 1);
- delay(1000);
- digitalWrite(ledPin, 0);
- digitalWrite(buzzerPin, 0);
- delay(1000);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement