Untitled
raw download clone
ARDUINO
views 16
,
size 2695 b
#include "FastLED.h"
#define NUM_LEDS 31
#define DATA_PIN 6
int trigPin=11;
int echoPin=12;
long duration,dist[10],avgDist;
unsigned long previousMillis2 = 0;
unsigned long previousMillis = 0;
unsigned long currentMillis;
unsigned long currentMillis2;
CRGB leds[NUM_LEDS];
int flag=0;
int warnFlag=0;
int cntOver=0;
void DetectDist();
void Green();
void setup() {
  Serial.begin(9600);   
  FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
  pinMode(trigPin, OUTPUT); 
  pinMode(echoPin, INPUT);
  delay(2000);
}
void loop() {
  currentMillis=millis();
  currentMillis2=millis();
  if(currentMillis-previousMillis>=1){
    DetectDist();
    if(avgDist>=50){
    cntOver++;
    }
    else {cntOver=0;}
    previousMillis=millis();
    }
  if(avgDist<50){
    if(!warnFlag){Warn();Warn();}
    RedDist();
    flag=0;
    cntOver=0;
    }
  else if(cntOver>=3 && avgDist>=50){
     if(!flag){
     Blue();
     flag=1;
     warnFlag=0;
     cntOver=0;
     }
  }
}
void DetectDist(){
  int max=0;
  int min=200;
  int sum=0;
  int tempDist;
  for(int i=0;i<10;i++){
    digitalWrite(trigPin,LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin,HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin,LOW);
    duration=pulseIn(echoPin,HIGH);
    tempDist=(duration/2)/29.4;
    if(tempDist>max)max=tempDist;
    else if(tempDist<min)min=tempDist;
    sum+=tempDist;
  }
  sum-=(min+max);
  avgDist=sum/8;
}
void Warn(){
    for(int j=0;j<50;j++){
      for(int i=0;i<NUM_LEDS;i++){
       leds[i]=CRGB(j,0,0);
      }
      FastLED.show();
      delay(10);
      }
    for(int j=0;j<50;j++){
      for(int i=0;i<NUM_LEDS;i++){
       leds[i]=CRGB(50-j,0,0);
      }
      FastLED.show();
      delay(10);
      }
    warnFlag=1;
  }
void RedDist(){
    //FastLED.clear();
    for(int i=0 ;i<NUM_LEDS;i++){
      leds[i]=CRGB(50,0,0);
      }
    int cnt=map(avgDist,0,50,0,NUM_LEDS-1);
    Serial.println(cnt);
    for(int i=0;i<cnt;i++){
      leds[i]=CRGB(0,50,0);}
    FastLED.show();
    delay(100);
  }

void Fade(){
    for(int j=0;j<=50;j++){
      for(int i=0;i<NUM_LEDS;i++){
       leds[i]=CRGB(50-j,j,0);
      }
      FastLED.show();
      delay(30);
      }     
  }
void Blue(){
  for(int i=0 ;i<NUM_LEDS;i++){
    leds[i]=CRGB(0,50,0);
  }
  FastLED.show();
  delay(300);
  int mid=NUM_LEDS/2;
  for(int i=NUM_LEDS/2; i>=0; i--){
    leds[mid+i]=CRGB(0,50,0);
    leds[mid-i]=CRGB(0,50,0);
    FastLED.show();
    delay(60);
    leds[mid+i]=CRGB(0,0,0);
    leds[mid-i]=CRGB(0,0,0);
    FastLED.show();
    delay(60);
  }
  FastLED.clear();
}
close fullscreen
Login or Register to edit or fork this paste. It's free.