#include <LiquidCrystal_I2C.h>
#include "pitches.h"
#define BUZZER_PIN 10
LiquidCrystal_I2C lcd(0x27, 16, 2);
int trig_pin = 2;
int echo_pin = 3;
long echotime;
float distance;
int melody[] = {
NOTE_E5, NOTE_D5, NOTE_FS4, NOTE_GS4,
NOTE_CS5, NOTE_B4, NOTE_D4, NOTE_E4,
NOTE_B4, NOTE_A4, NOTE_CS4, NOTE_E4,
NOTE_A4
};
int durations[] = {
8, 8, 4, 4,
8, 8, 4, 4,
8, 8, 4, 4,
2
};
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(trig_pin, OUTPUT);
pinMode(echo_pin, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
//pinMode(8, OUTPUT);
digitalWrite(trig_pin, LOW);
lcd.begin(16, 2);
lcd.setCursor(0,0);
lcd.print("DIST DTECTR v0.1");
lcd.setCursor(0,1);
lcd.print("LOADING...");
delay(2300);
}
void loop() {
loop1();
}
void loop1() {
lcd.clear();
digitalWrite(trig_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trig_pin, LOW);
echotime= pulseIn(echo_pin, HIGH);
distance= 0.0001*((float)echotime*340.0)/2.0;
lcd.setCursor(0,0);
lcd.println("Distance :");
lcd.setCursor(0,1);
lcd.print(distance);
lcd.print(" cm");
if(distance < 30)
{
loop2();
//digitalWrite(8, HIGH);
}
else
{
//digitalWrite(8, LOW);
}
delay(100);
}
void loop2() {
int size = sizeof(durations) / sizeof(int);
for (int note = 0; note < size; note++) {
//to calculate the note duration, take one second divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int duration = 1000 / durations[note];
tone(BUZZER_PIN, melody[note], duration);
//to distinguish the notes, set a minimum time between them.
//the note's duration + 30% seems to work well:
int pauseBetweenNotes = duration * 1.30;
delay(pauseBetweenNotes);
//stop the tone playing:
noTone(BUZZER_PIN);
}
}