// Sensor HC-SR04
#define TRIG_PIN 5
#define ECHO_PIN 4
#define BUZZER_PIN 2
// LED RGB
#define RED_PIN 14
#define GREEN_PIN 12
#define BLUE_PIN 13
#define Red 0, 255, 255
#define Green 255, 0, 255
#define Blue 255, 255, 0
#define Yellow 0, 0, 255
#define Purple 0, 255, 0
#define Off 255, 255, 255
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
}
void setColor(int r, int g, int b) {
digitalWrite(RED_PIN, r);
digitalWrite(GREEN_PIN, g);
digitalWrite(BLUE_PIN, b);
}
void loop() {
long duration;
float distance;
// Trigger
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Echo
duration = pulseIn(ECHO_PIN, HIGH);
// Distância
distance = duration * 0.034 / 2;
Serial.print("Distancia: ");
Serial.print(distance);
Serial.println(" cm");
// LED + BUZZER LOGIC
if (distance < 10) {
setColor(Red);
tone(BUZZER_PIN, 1000);
}
else if (distance < 35) {
setColor(Yellow);
tone(BUZZER_PIN, 1000);
delay(100);
noTone(BUZZER_PIN);
delay(100);
}
else if (distance < 60) {
setColor(Green);
tone(BUZZER_PIN, 1000);
delay(300);
noTone(BUZZER_PIN);
delay(300);
}
else {
setColor(0, 0, 0);
noTone(BUZZER_PIN);
}
delay(500);
}