Im trying to code an ultrasonic sensor that will blink when there is motion.
the code seems to work, but if the last state of the led is high when there is motion, it will stay high when there is no motion.
i want the led to reset back as low when there is no motion detected,
here is my code,
#define trigPin 2
#define echoPin 3
#define LED 13
unsigned long blinkTime = 0;
void blink(void)
{ static int x = 0; /* Current LED state 0=>off, 1=>on */
digitalWrite(LED,x ^= 1); /* Set LED to opposite state */
blinkTime = millis(); /* Schedule next state change */
}
void watch(void)
{ if (millis() - blinkTime >= 1) /* If it's time to change state */
blink(); /* then go do it */
}
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LED, OUTPUT);
}
void loop() {
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
watch();
}
delay(50);
}
any suggestion will be appriciated, thank you.