const byte brocheEcho = 10;
const byte brocheTrig = 11;
const byte brocheBuzz = 5;
const byte brocheLed = 4;
const unsigned int distanceSeuil = 50; // cm
const unsigned int deltaSeuil = 5; // cm
const unsigned long dureeBuzz = 1000; // ms
unsigned long chronoDebutBuzz;
enum {REPOS, ACTIVATION, ACTIF} etat = REPOS;
unsigned long distance() {
static unsigned long d;
const unsigned long periodeMesure = 100; // en ms => 10Hz (min 29ms entre 2 pings)
unsigned long chronoDerniereMesure = -periodeMesure;
if (millis() - chronoDerniereMesure >= periodeMesure) {
digitalWrite(brocheTrig, HIGH);
delayMicroseconds(10);
digitalWrite(brocheTrig, LOW);
d = pulseIn(brocheEcho, HIGH) / 58;
chronoDerniereMesure = millis();
}
return d;
}
void setup() {
pinMode(brocheBuzz, OUTPUT);
pinMode(brocheLed, OUTPUT);
pinMode(brocheTrig, OUTPUT);
pinMode(brocheEcho, INPUT);
}
void loop() {
switch (etat) {
case REPOS:
if (distance() < distanceSeuil) {
chronoDebutBuzz = millis();
tone(brocheBuzz, 500);
digitalWrite(brocheLed, HIGH);
etat = ACTIVATION;
}
break;
case ACTIVATION:
if (millis() - chronoDebutBuzz >= dureeBuzz) {
noTone(brocheBuzz);
etat = ACTIF;
} else {
if (distance() >= distanceSeuil + deltaSeuil) {
noTone(brocheBuzz);
digitalWrite(brocheLed, LOW);
etat = REPOS;
}
}
break;
case ACTIF:
if (distance() >= distanceSeuil + deltaSeuil) {
digitalWrite(brocheLed, LOW);
etat = REPOS;
}
break;
}
}