// ---------------------------------------------------------------- //
// ESP-8266 WEMOS D1 mini
// ---------------------------------------------------------------- //
#include <Adafruit_GFX.h>
#include <Adafruit_NeoPixel.h>
#define echoPin D5 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin D4 //attach pin D3 Arduino to pin Trig of HC-SR04
#define LED_PIN D6//datapin LED
#define LED_COUNT 12 // Popular NeoPixel ring size
#define BRIGHTNESS 100
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
//uint16_t RED =
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
Serial.println("with Arduino UNO R3");
strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
strip.show(); // Turn OFF all pixels ASAP
strip.setBrightness(BRIGHTNESS);
for(int i = 0; i < LED_COUNT+1; i++)
{
strip.setPixelColor(i, strip.Color(255, 255, 255)); // Set pixel's color (in RAM)
strip.show();
delay(50);
}
for(int i = 0; i < LED_COUNT+1; i++)
{
strip.setPixelColor(i, strip.Color(0, 0, 0)); // Set pixel's color (in RAM)
strip.show();
delay(50);
}
}
void loop(){
distanceMeasuring();
delay(25);
led(distance, 5);
}
void distanceMeasuring() {
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
// Serial.print("Distance: ");
// Serial.print(distance);
// Serial.println(" cm");
}
void led(int DISTANCE, int BUFFER){
int red_leds = 3;
int yellow_leds = 4;
for(int i = 1; i < DISTANCE - BUFFER ; i++)
{
strip.setPixelColor(i, strip.Color(255, 0, 0));
}
for(int i = red_leds; i < DISTANCE - BUFFER ; i++)
{
strip.setPixelColor(i, strip.Color(255, 255, 0));
}
for(int i = red_leds+yellow_leds+1; i < DISTANCE - BUFFER ; i++)
{
strip.setPixelColor(i, strip.Color(0, 255, 0));
}
for(int i = DISTANCE-BUFFER+1; i < LED_COUNT ; i++){
strip.setPixelColor(i, strip.Color(0, 0, 0)); // Set pixel's color (in RAM)
}
strip.setPixelColor(0, strip.Color(255, 0, 0));
strip.show();
}