/* y2. Esboçar um diagrama de ligações de Sonar e um Led (unicolor)
ligado ao Arduino.
Implemente código arduino que faz com que uma distância [20,200] cm medida
pelo sonar controla a frequência de ‘pisca’ intermitente do LED entre 1-80 Hz.
*/
#define echoPin 2 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 3 //attach pin D3 Arduino to pin Trig of HC-SR04
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
float t, f;
int led = 4;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
pinMode(led, OUTPUT);
Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
Serial.println("with Arduino UNO R3");
}
void led_pisca() {
digitalWrite(led, HIGH);
Serial.print("Frequencia: ");
Serial.println(f);
delay(t);
digitalWrite(led, LOW);
delay(t);
}
void loop() {
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
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; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.print("Distancia: ");
Serial.print(distance);
Serial.println(" cm");
if(distance > 19 and distance < 201){
f = map(distance, 20, 200, 1, 80);
t = (1/f)*1000;
led_pisca();
} else {
digitalWrite(led, LOW);
}
}