Goal

Write a sketch that :

  • read the distance to an obstacle using the ultrasonic sensor,
  • use that distance to decide how the led blinks :
    • every 1/2 seconds when distance is < 50cm,
    • every seconds when distance is between 50cm and 1m,
    • no blink when distance is over 1m

Solution

Instead of writing a "dummy" code that strictly follows the constraints, it is advisable to write a state machine, i.e. to separate the execution in "states", for which the µC does one particular thing. The execution passes from one state to another by detecting some various changes of conditions, in the present case, changes in the distance.

#include <HCSR04.h>

#define STATE_BLINK1 0
#define STATE_BLINK2 1
#define STATE_NOBLINK 2

#define PIN_TRIG 22
#define PIN_ECHO 19
#define PIN_LED 5

UltraSonicDistanceSensor distanceSensor(PIN_TRIG, PIN_ECHO);

int state = STATE_BLINK1;

void blink() {
  if (state == STATE_NOBLINK) {
    digitalWrite(PIN_LED, LOW);
    return;
  }
  digitalWrite(PIN_LED, HIGH);
  delay((state+1)*500);
  digitalWrite(PIN_LED, LOW);
  delay((state+1)*500);
}

void setup () {
    Serial.begin(115200);  
    pinMode(PIN_LED, OUTPUT);
    ledcAttach(PIN_LED, 1, 10);
    ledcWrite(PIN_LED, 512);
}

void loop () {
    // Every 500 miliseconds, do a measurement using the sensor and print the distance in centimeters.
    float distance = distanceSensor.measureDistanceCm();
    Serial.println(distance);
    if (distance < 50) {
      state = STATE_BLINK1;
    }
    else if (distance < 100) {
      state = STATE_BLINK2;
    }
    else {
      state = STATE_NOBLINK;
    }
    blink();
}