Advertisement
makispaiktis

Arduino - Sonar: Αισθητήρας που αλλάζει χρώμα σε LED

Apr 16th, 2019 (edited)
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <NewPing.h>
  2. #define red 8
  3. #define green 9
  4. #define blue 10
  5.  
  6. NewPing sonar(4,5, 300);
  7.  
  8. void setup() {
  9.   // put your setup code here, to run once:
  10.   Serial.begin(9600);
  11.   pinMode(red, OUTPUT);
  12.   pinMode(green, OUTPUT);
  13.   pinMode(blue, OUTPUT);
  14.   pinMode(3, INPUT);
  15.  
  16.   digitalWrite(red, HIGH);
  17.   digitalWrite(green, LOW);
  18.   digitalWrite(blue, HIGH);
  19.  
  20.   digitalWrite(3, HIGH);
  21.  
  22. }
  23.  
  24. void loop() {
  25.   // put your main code here, to run repeatedly:
  26.   int distance = sonar.ping_cm();
  27.  
  28.   if( distance <= 10) {
  29.     digitalWrite(red, LOW);
  30.     digitalWrite(green, HIGH);
  31.     digitalWrite(blue, HIGH);
  32.     Serial.print("Don't go any further, danger at ");
  33.     Serial.print(distance);
  34.     Serial.println(" cm");
  35.   }
  36.   else if ( distance <= 30 ) {
  37.     digitalWrite(red, HIGH);
  38.     digitalWrite(green, HIGH);
  39.     digitalWrite(blue, LOW);
  40.     Serial.print(distance);
  41.     Serial.println(" cm remaining, stop here or proceed carefully.");      
  42.   }
  43.   else if ( distance <= 50 ) {
  44.     digitalWrite(red, HIGH);
  45.     digitalWrite(green, LOW);
  46.     digitalWrite(blue, HIGH);
  47.     //Serial.println("Found obstacle at %d.", distance);    
  48.   }
  49.   else {
  50.     digitalWrite(red, HIGH);
  51.     digitalWrite(green, HIGH);
  52.     digitalWrite(blue, HIGH);
  53.     Serial.println("Drive safe!");  
  54.   }
  55.  
  56.   delay (500);
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement