Created
November 24, 2020 20:14
-
-
Save GreenMoonArt/50bbc206449562f79352793e8292493f to your computer and use it in GitHub Desktop.
NeoPixel measuring stick using an ultrasonic distance sensor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Measuring Stick | |
// Light up neopixel strip proportional to distance sensor reading | |
#include <Adafruit_NeoPixel.h> | |
#define LED_PIN 6 | |
#define LED_COUNT 10 | |
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800); | |
int trigPin = 12; | |
int echoPin = 13; | |
void setup() | |
{ | |
strip.begin(); | |
strip.setBrightness(127); // half brightness | |
strip.show(); | |
Serial.begin (9600); | |
pinMode(trigPin, OUTPUT); | |
pinMode(echoPin, INPUT); | |
} | |
void loop() | |
{ | |
int duration, distance, pixelsToLight; | |
int ledCount = LED_COUNT; | |
float flPixels; | |
float maxDistance = 300.0; // you can adjust this to your situation | |
digitalWrite(trigPin, HIGH); | |
delayMicroseconds(1000); | |
digitalWrite(trigPin, LOW); | |
duration = pulseIn(echoPin, HIGH); | |
distance = (duration/2) / 29.1; | |
// emulate a traffic light | |
if (distance >= 300 || distance <= 0) | |
{ | |
Serial.println("Out of range"); | |
strip.setPixelColor(0, 0, 0, 0); | |
strip.setPixelColor(1, 0, 0, 0); | |
strip.setPixelColor(2, 0, 0, 0); | |
strip.show(); | |
} | |
else | |
{ | |
Serial.print(distance); | |
Serial.println(" cm"); | |
flPixels = (distance / maxDistance) * ledCount; | |
pixelsToLight = flPixels; // int will truncate to right of decimal | |
Serial.print(pixelsToLight); | |
Serial.println(" pixels"); | |
//first clear all pixels | |
for(int i=0; i < LED_COUNT; i++) | |
{ | |
strip.setPixelColor(i, 0, 0, 0); | |
} | |
//light pixels according to distance measured | |
for(int i=0; i < pixelsToLight; i++) | |
{ | |
strip.setPixelColor(i, 0, 127, 0); //this is a green -- you can use any color you like | |
} | |
strip.show(); | |
} | |
delay(100); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment