View difference between Paste ID: eRKmbKE1 and zFBuZYN2
SHOW: | | - or go back to the newest paste.
1
#include <Adafruit_NeoPixel.h>
2
#define PIN 6
3
#define NUMPIXELS 10
4
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
5
// defines pins numbers
6
#define trigPin 11
7
#define echoPin 10
8
void setup() {
9
  pinMode(trigPin, OUTPUT); // trigPin as an Output
10
  pinMode(echoPin, INPUT); // echoPin as an Input
11
  Serial.begin(9600); // Starts the serial communication
12
  pixels.begin(); // INITIALIZE NeoPixel strip object
13
  pixels.clear(); // Set all pixel colors to 'off'
14
}
15
void loop() {
16
int distance = measureDistance();
17
  // Prints the distance on the Serial Monitor
18
  Serial.print("Distance: ");
19
  Serial.println(distance);
20
  set_colour(distance);
21
  delay(200);
22
}
23
int measureDistance(){
24
  long duration;
25
  int distance;
26
  // Clears the trigPin
27
  digitalWrite(trigPin, LOW);
28
  delayMicroseconds(2);
29
  // Sets the trigPin on HIGH state for 10 micro seconds
30
  digitalWrite(trigPin, HIGH);
31
  delayMicroseconds(10);
32
  digitalWrite(trigPin, LOW);
33
  // Reads the echoPin, returns the sound wave travel time in microseconds
34
  duration = pulseIn(echoPin, HIGH);
35
  // Calculating the distance
36
  distance= duration*0.034/2;
37
  return distance;
38
}
39
void set_colour(int distance){
40
  int r,g,b,l;
41
  if(distance>200){
42
    r=0;
43
    g=255;
44
    b=0;
45
    l=10;
46
  } else {
47
  	r=map(distance,0,200,255,0);
48
    g=map(distance,0,200,0,255);
49
    b=0;
50
    l=map(distance,0,200,1,10);
51
  }
52
  for(int i=0; i<10; i++){
53
    if(i<l)
54
      pixels.setPixelColor(i, pixels.Color(r, g, b));
55
    else
56
      pixels.setPixelColor(i, pixels.Color(0,0,0));
57
  }
58
  pixels.show();   // Send the updated pixel colors to the hardware.
59
}
60