/*
HC-SR04 Ultrasonic Sensor Example.
Turn the LED on when an object is within 100cm range.
Copyright (C) 2021, Uri Shaked
*/
#include<Servo.h>
#define ECHO_PIN 2
#define TRIG_PIN 3
Servo myservo;
int pos;
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
myservo.attach(7);
}
float readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
void loop() {
float distance = readDistanceCM();
if(distance>385)
{
digitalWrite(LED_BUILTIN,HIGH);
Serial.println("Distancs");
Serial.println(distance);
Serial.println("Motor is on");
for(int pos=0;pos<=180;pos++)
{
myservo.write(pos);
delay(10);
}
for(int pos=180;pos>=0;pos--)
{
myservo.write(pos);
delay(10);
}
}
delay(100);
}