[code]
int trigPin=12;
int echoPin=11;
int pingTravelTime;
float pingTravelDistance;
float distanceToTarget;
int LEDpin=2;
int ledState = LOW; //used to set the LED
unsigned long previousMillis=0; //Stores the last time the LED was updated
const long blinkTime = 3000; //interval light stays on after distanceToTarget is <=2"
void setup() {
// put your setup code here, to run once:
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LEDpin, OUTPUT);
Serial.begin(9600);
}
void loop() {
// time LED remains on after triggered because distanceToTarget reaches ,+2.
digitalWrite(trigPin, LOW);
delayMicroseconds(10);
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pingTravelTime=pulseIn(echoPin,HIGH);
pingTravelDistance=(pingTravelTime*765.*5280.*12.)/(3600.*1000000);
distanceToTarget=pingTravelDistance/2;
Serial.print("Your Distance to Target in inches is: ");
Serial.println(distanceToTarget);
unsigned long currentMillis=millis();
if(distanceToTarget<=2.){
long time_since_last_reset = millis(); //code from this point found on philo mech website
while((millis()-time_since_last_reset)<=blinkTime){
digitalWrite (LEDpin, HIGH);
if ((millis()-time_since_last_reset)>blinkTime){
digitalWrite (LEDpin, LOW);
delay (blinkTime); //could also use the for loop for(;;){ but this permentantl stops the loop.
}
}
if(distanceToTarget<=2.){
long time_since_last_reset = millis(); //code from this point found on philo mech website
while((millis()-time_since_last_reset)<=blinkTime){
digitalWrite (LEDpin, HIGH);
if ((millis()-time_since_last_reset)>blinkTime){
digitalWrite (LEDpin, LOW);
delay (blinkTime);
}
}
}
}
}
[/code]
I'm new, so apologies if this post is not well formatted. I'm using an UNO R3 and HCSRO4 ultrasonic sensor and an LED.
I want the LED to turn on when when within 2" of an object, then turn off after 3 seconds, which the above code accomplishes. I then want the LED to stay off until the object is more than 2" away, at which point I want the LED to turn on, then turn off after 3 seconds. I then want the LED to stay off until the object is within 2", etc. I have tried to make interrupts, delays, and change states work. I'm either doing them wrong or have not selected the correct method for achieving this. Can anyone head me in the right direction? Thanks.