Skip to content

Instantly share code, notes, and snippets.

@chris-gunawardena
Created January 27, 2017 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chris-gunawardena/9f5cd3ddc274d5f9227de58499d4f588 to your computer and use it in GitHub Desktop.
Save chris-gunawardena/9f5cd3ddc274d5f9227de58499d4f588 to your computer and use it in GitHub Desktop.
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN 6
#define NUM_LEDS 30
#define BRIGHTNESS 255
const int TrigPin = 10;
const int echoPin = 13;
String state = "off";
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRBW + NEO_KHZ800);
void setup() {
Serial.begin(9600);
pinMode(TrigPin, OUTPUT);
pinMode(echoPin, INPUT);
strip.setBrightness(BRIGHTNESS);
strip.begin();
strip.show();
rainbow(3);
setWhite(0);
}
void loop() {
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(5);
digitalWrite(TrigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
long cm = microsecondsToCentimeters(duration);
if(0 < cm && cm <= 5) {
// switch off
state = "off";
setWhite(0);
} else if(5 < cm && cm < 40) {
// set brightness
state = "on" + String(cm);
setWhite((255*cm)/40);
} else {
Serial.println("40+");
}
Serial.println(state);
delay(50);
}
void setWhite(int brightness) {
for(uint16_t i=0; i<strip.numPixels(); i++) {
strip.setPixelColor(i, strip.Color(0,0,0, brightness ) );
}
strip.show();
}
long microsecondsToCentimeters(long microseconds) {
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
void rainbow(uint8_t wait) {
uint16_t i, j;
for(j=0; j<256; j++) {
for(i=0; i<strip.numPixels(); i++) {
strip.setPixelColor(i, Wheel((i+j) & 255));
}
strip.show();
delay(wait);
}
}
// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
WheelPos = 255 - WheelPos;
if(WheelPos < 85) {
return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3,0);
}
if(WheelPos < 170) {
WheelPos -= 85;
return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3,0);
}
WheelPos -= 170;
return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0,0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment