/*float ultrasonic_distance_cm(int trigPin, int echoPin){
digitalWrite(trigPin, LOW);
digitalWrite(echoPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
unsigned long sonic_duration = pulseIn(echoPin, HIGH);
float distance_cm = (sonic_duration / 2.0) / 29.1;
return distance_cm;
}
void setup() {
Serial.begin(9600);
pinMode(12, OUTPUT);
pinMode(13, INPUT);
}
void loop() {
Serial.println(ultrasonic_distance_cm(12, 13));
delay(100);
*/
const int ledPin = 6; // The pin of your LED
const int trigPin = 5; // The pin to which the TRIG is connected
const int echoPin = 4; // The pin to which the ECHO is connected
const int ledOnTime = 1000; // The time that the LED stays on, after detecting the motion (in milliseconds, 1000ms = 1s)
const int trigDistance = 20; // The distance (and lower than it) at which the sensor is triggered (in centimeters)
int duration;
int distance;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
digitalWrite(trigPin, HIGH);
delay(1);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
if (distance <= trigDistance) {
digitalWrite(ledPin, HIGH);
delay(ledOnTime);
digitalWrite(ledPin, LOW);
}
delay(100);
}