#define ECHO_PIN 4
#define TRIG_PIN 5
#define LED 13
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED, OUTPUT);
}
int readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return round(duration * 0.0342 / 2);
}
void loop() {
// put your main code here, to run repeatedly:
int distance = readDistanceCM();
if (distance<100){
digitalWrite(LED, HIGH);
} else {
digitalWrite(LED, LOW);
}
}