Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Adafruit_NeoPixel.h>
- #define PIN 6
- #define NUMPIXELS 10
- Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
- // defines pins numbers
- #define trigPin 11
- #define echoPin 10
- void setup() {
- pinMode(trigPin, OUTPUT); // trigPin as an Output
- pinMode(echoPin, INPUT); // echoPin as an Input
- Serial.begin(9600); // Starts the serial communication
- pixels.begin(); // INITIALIZE NeoPixel strip object
- pixels.clear(); // Set all pixel colors to 'off'
- }
- void loop() {
- int distance = measureDistance();
- // Prints the distance on the Serial Monitor
- Serial.print("Distance: ");
- Serial.println(distance);
- set_colour(distance);
- delay(200);
- }
- int measureDistance(){
- long duration;
- int distance;
- // Clears the trigPin
- digitalWrite(trigPin, LOW);
- delayMicroseconds(2);
- // Sets the trigPin on HIGH state for 10 micro seconds
- 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;
- return distance;
- }
- void set_colour(int distance){
- int r,g,b,l;
- if(distance>200){
- r=0;
- g=255;
- b=0;
- l=10;
- } else {
- r=map(distance,0,200,255,0);
- g=map(distance,0,200,0,255);
- b=0;
- l=map(distance,0,200,1,10);
- }
- for(int i=0; i<10; i++){
- if(i<l)
- pixels.setPixelColor(i, pixels.Color(r, g, b));
- else
- pixels.setPixelColor(i, pixels.Color(0,0,0));
- }
- pixels.show(); // Send the updated pixel colors to the hardware.
- }
Add Comment
Please, Sign In to add comment