While distance is, do this for 10 seconds.

Hello everyone, I'm trying to code a box that detects the distance (to 10cm), and blinks 2 LEDs for 10 seconds, then continue with the loop. I have read a lot of articles and topics from google looking for an answer to this but I got no luck.

Any idea on getting this done? I'm thinking of making a "function" (void blink() { 2led_blink_code }) but have no idea how to program the " while distance == 10 for 10 seconds { blink(); }.

Thanks.

When the distance becomes equal to 10 cm save the current value of millis(). Check whether 10 seconds has passed by subtracting the start time from millis() at each pass through loop() until the period has passed.

Whilst waiting for the period to pass blink the LEDS but no blocking code must be executed. Use millis() for timing the LED blinks as in the BlinkWithoutDelay example program.

Note that loop() continues to run freely at all times using this technique.

Hey there, thank you for your reply. While I searched the forum, found a code and decided to use it.

This is what I got until now:

/*
 * created by Rui Santos, http://randomnerdtutorials.com
 * 
 * Complete Guide for Ultrasonic Sensor HC-SR04
 *
    Ultrasonic sensor Pins:
        VCC: +5VDC
        Trig : Trigger (INPUT) - Pin11
        Echo: Echo (OUTPUT) - Pin 12
        GND: GND
 */
unsigned long overallStartTime;
unsigned long blinkStartTime;
unsigned long overallPeriod = 5000;
unsigned long blinkPeriod = 200;
unsigned long currentTime;
const byte ledvs1 = 9;
const byte ledvs2 = 10;
boolean blinking = true;
int trigPin = 11;    //Trig - green Jumper
int echoPin = 12;    //Echo - yellow Jumper
long duration, cm, inches;

void setup() {
  //Serial Port begin
  Serial.begin (9600);
  pinMode(ledvs1, OUTPUT);
  pinMode(ledvs2, OUTPUT);  
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  overallStartTime = millis();
  blinkStartTime = overallStartTime;
}

void loop()
{
distance();
cm = 0;
delay(1000);
}

void distance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  cm = (duration/2) / 29.1; 
  Serial.print(cm);
  Serial.println();
  while(cm == 8) {
  currentTime = millis();
  if (currentTime - blinkStartTime >= blinkPeriod && blinking)  //LED blink time check
  {
    Serial.println("blink");
    digitalWrite(ledvs1, !digitalRead(ledvs1));
    digitalWrite(ledvs2, !digitalRead(ledvs2));//change state of LED
    blinkStartTime = blinkStartTime + blinkPeriod;  //save the new blink start time
  }

  if (currentTime - overallStartTime >= overallPeriod && blinking)  //overall time check
  {
    blinking = false;
    digitalWrite(ledvs1, LOW);
    digitalWrite(ledvs2, LOW);
    Serial.println("Time's up.  Stopped blinking");
    return;
  }
  return;
 }
}

However, this blinks my LEDs for 5 seconds but then it stops. Even if I get a 8cm distance again, it won't blink anymore. I have absolutely no idea how to count 10 seconds of 8cm distance and blink those two LEDs while those 10 seconds pass.

Your while(cm == 8) block contains a return statement. The while statement will iterate exactly once.

If you remove the return statement at the end of the block, you will have an infinite loop, since the value of cm never changes, while the while loop is running.

Your whole premise, that you need to blink the LED for 10 seconds, while the distance is less than 8, is flawed. You either want to blink the LED for the whole time the distance is less than 8, or you want to blink the LED for 10 seconds IF the distance is less than 8.

While distance is, do this for 10 seconds.

Us humans are used to describing problems using that sort of language but it is not actually an accurate reflection of the problem. It is better stated as While If distance is, do this for 10 seconds.

The demo Several Things at a Time illustrates how to use millis() to manage timing.

...R

You also may need to clarify in your own mind if you need to blink for the full 10 seconds starting when the distance becomes <10, but goes back to being >10 during the 10s of blink. (Unless that’s physically impossible of course.)

Thanks everyone for your replies.

The thing that I’m trying to do is to have a HC-SR04 sensor that measures distance (as step 1 of 4), and when the distance becomes 8 centimeters, the LEDs to blink, and if the value becomes > than 8 cm or < than 8 cm, the LEDs to stop blinking.

So, the thing I’m trying to do is to blink the LEDs for 10 seconds ONLY IF the distance is 8 cms, if the distance changes, to stop blinking. If the distance is the same for 10 seconds ( 8cm for 10 seconds ) the LEDs to blink, and then to pass on to step 2.

I suspect that you will never get the distance to be 8cm even if the thing isn't moving, dues to fluctuations in the reading. I'd suggest you go for between say 7 and 9, but you should test that sort of threshold.

manor_royal: I suspect that you will never get the distance to be 8cm even if the thing isn't moving, dues to fluctuations in the reading. I'd suggest you go for between say 7 and 9, but you should test that sort of threshold.

Isn't 8 the only number between 7 and 9?

Thanks again for your reply. Ever with the distance between 7 to 9, I don't know how to blink the LEDs only if the distance is set, and also to cancel the blinking if the distance has changed (less than 7~9, or more than 7~9).

I think he meant that the reading will not be accurate, so I must edit the script and edit the values and set them from 7 to 9.

Dragosh: Hello everyone, I'm trying to code a box that detects the distance (to 10cm), and blinks 2 LEDs for 10 seconds, then continue

What distance are you measuring? What is it that is moving toward or away from the box?

Is it your hand, a turtle, a rocket. Does is somehow know what 8cm is?

Depending on how quickly the distances may change (of whatever you are measuring) will require you to make your code correspondingly responsive.

so, what are you measuring?

I think he meant that the reading will not be accurate, so I must edit the script and edit the values and set them from 7 to 9.

That depends on whether you mean >7 && <9 or >=7 && <=9.

Put your code to blink the LED in a function. Call that function under the right conditions.

When you try to do that, you’ll discover that in the blinkTheLED function, you don’t know whether the LED should be blinking, or not.

You’ll discover that you will have difficulties writing the statement to call the function, because you keep saying while when you mean if.

You’ll discover that you need to decide whether to call the blinkTheLED() function IF the distance is >= some value AND <= some other value.

You’ll discover that you really need to call blinkTheLED() regardless of the distance. You’ll discover that you need a boolean variable to define whether the LED should be blinking, that you check in the function. If the LED is not supposed to be blinking, turn it off.

You’ll discover that you need to set the flag to true when the distance is in the blink-the-LED range, and set the flag to false if the distance is not in the blinky range.

@BulldogLowell, measuring the distance until my palm gets to 8 centimeters, after that, I need it to blink the LEDs for 10 seconds only if the distance is 8 centimeters, if I take my palm away, the LEDs need to stop blinking and "reset" (wait for the distance to be 8 again), and if 10 seconds passed and the distance was 8cm, to do a Serial.print.

@PaulS, you set me off to Riddle mode. I'll try to follow up your guide and post a reply with my result.

Thanks both for your replies.

How close to 8cm must the distance stay for it to be considered still 8cm ? It is unlikely that the value returned by the sensor will be stable even if the distance remains the same. This is particularly the case if your hand has to stay in exactly the same place for 10 seconds.

Hello again everyone and thank you for your replies.
I have managed to work this out the way @PaulS told me to.

@UKHeliBob, the hand must be at 8 cm distance from the sensor for about 10 seconds.
This is a mystery box so it doesn’t need to much precision as it’s just a game.

The final code that I got is:

unsigned long currentTime  = 0;
unsigned long pastTime     = 0;
int           currentState = 0;
unsigned long seconds = 0;


f (cm > 7 && cm < 9)
  {
    pastTime    = currentTime;
    currentTime = millis();
    unsigned long timePassed = currentTime - pastTime;
    if (timePassed >= 1000);
            {
            seconds ++;
               pastTime = currentTime;
               blitz(); // BlinkWIthoutDelay LEDs
            }
   if ( seconds == 20 ) {
    Serial.print("Ready!");
    Serial.println();
    seconds = 0; 
    steps = 2;
    Serial.print("Step 2");

Thanks everyone for your support and replies!

The final code that I got is:

But you did not post all of it.

UKHeliBob: But you did not post all of it.

All of it it's not finished, this is the "steps" part that I was missing. There will be 4 steps, and I just finished the first one, but can adapt the other ones to this code.

All of it it's not finished,

So not

The final code

after all.

No wonder I am confused

UKHeliBob: So notafter all.

No wonder I am confused

I was talking about the code that I needed, which was the subject of this topic. :)