arduino-course/Week 2/Ultrasonic/Ultrasonic.ino

48 lines
753 B
Arduino
Raw Normal View History

2019-11-15 23:55:30 +01:00
// Ultrasonic sensor
#include <SR04.h>
#define red 3
#define yellow 4
#define green 5
#define echo 9
#define trig 8
SR04 sr04 = SR04(echo, trig);
long length;
void turnOff() {
digitalWrite(red, LOW);
digitalWrite(yellow, LOW);
digitalWrite(green, LOW);
}
void turnOn(int LED) {
turnOff();
digitalWrite(LED, LOW);
}
void setup(){
Serial.begin(9600);
pinMode(red, OUTPUT);
pinMode(yellow, OUTPUT);
pinMode(green, OUTPUT);
pinMode(echo, INPUT);
pinMode(trig, OUTPUT);
}
void loop() {
length = sr04.Distance();
Serial.println("Distancia: ");
Serial.println(length);
Serial.println("cm");
if(length < 8){
turnOn(red);
} else if (length < 15){
turnOn(yellow);
} else {
turnOn(green);
}
delay(100);
}