Skip to content

Instantly share code, notes, and snippets.

@ayoussef127
Created July 2, 2018 13:30
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 ayoussef127/50f8ef60f1a71c255a862427410b2120 to your computer and use it in GitHub Desktop.
Save ayoussef127/50f8ef60f1a71c255a862427410b2120 to your computer and use it in GitHub Desktop.
Distance sensor with for loop
#include <FastLED.h>
#define NUM_LEDS 200
#define datapin 6
#define LED_TYPE WS2811
CRGB leds[NUM_LEDS];
const int trigPin = 10;
const int echoPin = 11;
// defines variables
long duration;
int distance;
void setup() {
FastLED.addLeds<WS2811, datapin>(leds, NUM_LEDS);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void loop() {
//distance code
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;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
// main code
if (distance < 40) {
for (int i =0; i < 200; i++)
{
fill_solid(leds, NUM_LEDS, CRGB(255, 255, 0));
FastLED.show();
delay (10);
}
}
else {
fill_solid(leds, NUM_LEDS, CRGB::Black);
FastLED.show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment