Created
July 2, 2018 13:30
-
-
Save ayoussef127/50f8ef60f1a71c255a862427410b2120 to your computer and use it in GitHub Desktop.
Distance sensor with for loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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