#script test distance

Dernière modification : 2016/12/19 02:29

Ce script affiche la distance avec sonar HC-SR04

http://teciel.free.fr/scripts/testdistance.ino

  #include <ESP8266WiFi.h>
#define TRIGGER 5
#define ECHO    4

// NodeMCU Pin D1 > TRIGGER | Pin D2 > ECHO
int ledPin = D0; // GPIO13
void setup() {
    Serial.begin (9600);
  pinMode(TRIGGER, OUTPUT);
  pinMode(ECHO, INPUT);
  pinMode(BUILTIN_LED, OUTPUT);
  
  delay(10);
 
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
 
}
 
void loop() {

    long duration, distance;
  digitalWrite(TRIGGER, LOW);  
  delayMicroseconds(2); 
  
  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10); 
  
  digitalWrite(TRIGGER, LOW);
  duration = pulseIn(ECHO, HIGH);
  distance = (duration/2) / 29.1;

 
  // Match the request
 
  int value = LOW;
  if (distance <= 10)  {
 digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level)
 delay(20); // wait for 2 second
 digitalWrite(ledPin, LOW); // turn the LED off by making the voltage LOW
 delay(20); 
 digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level)
 delay(20); // wait for 2 second
 digitalWrite(ledPin, LOW); // turn the LED off by making the voltage LOW
 delay(20); 
 digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level)
 delay(20); // wait for 2 second
 digitalWrite(ledPin, LOW); // turn the LED off by making the voltage LOW
 delay(20); 
  }
else  {
    digitalWrite(ledPin, HIGH);
    value = HIGH;
  }
 
// Set ledPin according to the request
digitalWrite(ledPin, value);

 
  delay(1);
Serial.print(distance);
Serial.println(" cm");

delay(50);

}