#include <Servo.h>
const int TRIG_PIN = 9;
const int ECHO_PIN = 8;
const int servoPin = 10;
Servo servo;
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
servo.attach(servoPin, 500, 2400);
}
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();
Serial.println(distance);
if(distance <= 100)
{
servo.write(90);
delay(500);
} else
{
servo.write(0);
delay(500);
};
}