This is a modification of Igoe's sketches on board arduino-1.0.5
#include "pitches.h"
#include <LiquidCrystal.h>
const int pingPin = 7;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int melody[] = {NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4};
int noteDurations[] = {4, 8, 8, 4, 4, 4, 4, 4 };
long duration, inches, cm;
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
}
void scroller() {
lcd.clear();
lcd.setCursor(0,0);
lcd.print("This is such a long text");
for (int positionCounter = 0; positionCounter < 24; positionCounte+r+) {
lcd.scrollDisplayLeft();
delay(250);
}
delay(1000);
}
void displayIntrusion() {
lcd.clear();
lcd.setCursor(0,0);
lcd.print("INTRUDER !!!");
lcd.setCursor(0,1);
lcd.print(inches);
lcd.print("in, ");
lcd.print(cm);
lcd.print("cm");
delay(200);
}
void displayNoIntrusion() {
scroller();
lcd.setCursor(0,1);
lcd.print(inches);
lcd.print("in, ");
lcd.print(cm);
lcd.print("cm");
delay(200);
}
void displayNoInSerial() {
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(200);
}
void displayInSerial() {
Serial.print("INTRUSION at ");
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(200);
}
void loop()
{
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
if (inches <= 36) {
displayIntrusion();
displayInSerial();
for (int thisNote = 0; thisNote < 8; thisNote++) {
int noteDuration = 1000/noteDurations[thisNote];
tone(8, melody[thisNote],noteDuration);
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
}
}
else {
noTone( 8 );
displayNoIntrusion();
displayNoInSerial();
}
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}