Make something happen every X seconds on Arduino

645 views Asked by At

So, I want to make a hand sanitizer. I have an ultra-sonic sensor.

Right now it works like this: when distance is lower than 5cm, it pours liquid.

What I want to do is: when distance < 5 cm, pour for 2 seconds. After the 2 second have passed, wait another 3 seconds before measuring again.

Ex: I put my hand in front on sensor, it pours liquid for 2 seconds. After that it waits for 3 seconds then it's ready to pour again if distance < 5 cm.

Thank you, it would be of much help. I really don't know how to implement a timer like this.

1

There are 1 answers

0
earthling On
#define DISTANCE_IN_MM          50u
#define DISPENSE_DURATION_IN_MS 2000u
#define DISPENSE_TIMOUT_IN_MS   3000u

// Function declarations.
//
uint16_t ultrasonic_sensor_get_distance();
void     turn_dispenser_on();
void     turn_dispenser_off();

void loop()
{
    // Poll sensor distance. If under threshold, pour.
    //
    if (DISTANCE_IN_MM >= ultrasonic_sensor_get_distance())
    {
        turn_dispenser_on();
        delay(DISPENSE_DURATION_IN_MS);
        turn_dispenser_off();
        delay(DISPENSE_TIMOUT_IN_MS);
    }
}