Distancing Hat




 
#define FASTLED_ESP8266_RAW_PIN_ORDER
#include <FastLED.h>

// define pins numbers
const int trigPin = 4;   //D2
const int echoPin = 5;   //D1
const int alertPin = 14; //D5
const int ledPin = 12;   //D6

// Define the approach distances centimetres.
const int alertDistance = 200;  // Alarm sounds red led
const int yellowDistance = 280; // Yellow led

// led colours
int red = 0xff0000;
int yellow = 0xff5b00;
int green = 0x00ff00;

// About the leds
#define NUM_LEDS 3
#define LED_PIN ledPin
#define LED_TYPE PL9823

// Tell the library about the number of leds
CRGB led[NUM_LEDS];

// define distance variables
long duration;
int distance;

void setup() {
  pinMode(trigPin, OUTPUT);  // Set the trigPin as an Output
  pinMode(echoPin, INPUT);   // Set the echoPin as an Input
  pinMode(alertPin, OUTPUT); // Set the alert to output.
  Serial.begin(9600); // Start the serial communication

  // Initialize the fast led library
  FastLED.addLeds<LED_TYPE, LED_PIN>(led, NUM_LEDS);
  delay(1000);

  // Set the initial led colours
  led[0] = 0x000000;  // pilot light and 5v drop through diode
  led[1] = led[2] = green;
}

void loop() {
  // Clear the trigger pin and alert pin
  digitalWrite(trigPin, LOW);
  digitalWrite(alertPin, LOW);
  delayMicroseconds(2);

  // Set the trigger pin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  // Calculate the distance - speed of sound is 343 mps
  distance = duration * 0.0343 / 2;

  // Set the leds to green
  led[1] = led[2] = green;

  if (distance < yellowDistance) {
    led[1] = led[2] = yellow;
  }
  if (distance < alertDistance) {
    digitalWrite(alertPin, HIGH);
    led[1] = led[2] = red;
  }
  // Display the set led colour.
  FastLED.show();
  delay(200);
 
  // Display the distance on the Serial Monitor
  Serial.print("Distance cm: ");
  Serial.println(distance);
}