|
-Igor 2-26-13
|
Arduino source code for this example:
[cpp]
/*
Sample code for ‘smart garbage’ demo
I wrote this code with snippets from Arduino Tone example and the ping example from :
http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/
-Igor Ramos 2-25-2013
*/
#include “pitches.h”
//8-ohm speaker on digital pin 8
#define trigPin 13
#define echoPin 12
// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
4, 8, 8, 4,4,4,4,4 };
void setup() {
Serial.begin(9600); // Open serial monitor at 115200 baud to see ping results.
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.println(“starting”);
}
void loop() {
static char dist=0;
long int time;
static long int prev_time=0,prev_time2=0;
long duration, distance;
time = millis();
if ( time – prev_time > 50)
{
prev_time = time;
digitalWrite(trigPin, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if ((dist ==0 ) && (distance <30) && (distance >5))
{
dist = 1; //set alarm
Serial.println(“ALARM SET……….”);
}
if ((dist ==1 ) && (distance >20) && (distance <199))
{
dist = 0; //clear alarm
Serial.println(“Playing tone…….”);
my_play_tone();
delay(2000);
}
if ( time – prev_time2 > 1000)
{
prev_time2 = time;
Serial.print(“distance:”);
Serial.print(distance);
Serial.print(” cm, alarm:”);
Serial.println(dist, DEC);
}
}
}
void my_play_tone() {
// iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 8; thisNote++) {
// 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 noteDuration = 1000/noteDurations[thisNote];
tone(8, melody[thisNote],noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note’s duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(8);
}
}
[/cpp]
References: