#photosonar.ino

Dernière modification : 2016/12/20 12:50

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

int photocellPin = A0;     
int photocellReading;     
int LEDbrightness;     
int ledPin = D0;

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); 
    delay(20); 
    digitalWrite(ledPin, 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);

  photocellReading = analogRead(photocellPin);  
  Serial.print("Analog reading = ");
  Serial.println(photocellReading);     // the raw analog reading
  photocellReading = 1023 - photocellReading;
  LEDbrightness = map(photocellReading, 0, 1023, 0, 255);
  analogWrite(ledPin, LEDbrightness);
  delay(100);

}