Skip to content

Instantly share code, notes, and snippets.

@netmaniac
Created November 29, 2017 08:01
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 netmaniac/52abe6233e98609cb58b645377e28cc5 to your computer and use it in GitHub Desktop.
Save netmaniac/52abe6233e98609cb58b645377e28cc5 to your computer and use it in GitHub Desktop.
#include <Adafruit_NeoPixel.h>
#include <NewPing.h>
#define LED_PIN 6 // Pin, do którego podłączony jest "DIN" z NeoPixeli
#define LEDS_COUNT 8 // Ilość diod na pasku NeoPixel
#define BUZZER_PIN 9 // Pin buzzera
#define TRIGGER_PIN 12 // Pin "TRIG" czujnika odległości
#define ECHO_PIN 11 // Pin "ECHO" czujnika odległości
#define MAX_DISTANCE 200 // Maksymalny możliwy do zmierzenia dystans (200 dla HC-SR04)
#define TRIG_DISTANCE 100 // Dystans od którego zaczniemy informować o przeszkodzie
#define MEASUREMENT_PERIOD 200 // Co ile ms ma być wykonywany pomiar odległości?
#define BEEP_TIME 50 // Ile ms ma trwać piszczenie buzzera?
Adafruit_NeoPixel leds(LEDS_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
unsigned int distance = 0; // Aktualna odległość
unsigned long lastDistanceMeasurementTime = 0; // Czas wykonania ostatniego pomiaru odległości
void setup() {
pinMode(BUZZER_PIN, OUTPUT);
leds.begin();
}
void loop() {
if(millis() - lastDistanceMeasurementTime >= MEASUREMENT_PERIOD) {
distance = sonar.ping();
distance = sonar.convert_cm(distance);
lastDistanceMeasurementTime = millis();
}
led_displayDistance(distance);
buzzer_beepDistance(distance);
}
void led_setHue(int pixel, int hue) {
hue = hue % 360;
int r,g,b;
if(hue < 60) {
r = 255;
g = map(hue, 0, 59, 0, 254);
b = 0;
} else if(hue < 120) {
r = map(hue, 60, 119, 254, 0);
g = 255;
b = 0;
} else if(hue < 180) {
r = 0;
g = 255;
b = map(hue, 120, 179, 0, 254);
} else if(hue < 240) {
r = 0;
g = map(hue, 180, 239, 254, 0);
b = 255;
} else if(hue < 300) {
r = map(hue, 240, 299, 0, 254);
g = 0;
b = 255;
} else {
r = 255;
g = 0;
b = map(hue, 300, 359, 254, 0);
}
leds.setPixelColor(pixel, r, g, b);
}
void led_turnOff(int pixel) {
leds.setPixelColor(pixel, 0, 0, 0);
}
void led_displayDistance(int distance) {
int numLeds = map(distance, 0, TRIG_DISTANCE, LEDS_COUNT, 0);
if(distance == 0) numLeds = 0;
for(int x = 0; x < LEDS_COUNT; x++) {
if(x < numLeds) {
led_setHue(x, 120 - (120/LEDS_COUNT) * x);
} else {
led_turnOff(x);
}
}
leds.show();
}
void buzzer_beepDistance(int distance) {
int beepsPerSecond = map(distance, 0, TRIG_DISTANCE, LEDS_COUNT, 0);
if(beepsPerSecond == 0 || distance == 0) {
digitalWrite(BUZZER_PIN, LOW);
return;
}
int period = 1000 / beepsPerSecond;
if(beepsPerSecond == LEDS_COUNT) {
period = BEEP_TIME;
}
analogWrite(BUZZER_PIN, 128 * (millis() % period < BEEP_TIME));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment