Fritzing image
Resistor 100ohm
Sensor Ping Parallax
Buzzer
Led
Arduino code
/* 2 sept 2011 - Massimo Pacilio Distance detector. Sensor: Ground, DigitalPin 7, 5V Buzzer: Ground, DigitalPin 8 Led: Ground, DigitalPin 13 This code is in public domain */ const unsigned int BUZZER_PIN = 8; const unsigned int PING_SENSOR_IO_PIN = 7; const unsigned int LED_PIN = 13; void setup() { pinMode(LED_PIN, OUTPUT); pinMode(BUZZER_PIN, OUTPUT); } void loop() { pinMode(PING_SENSOR_IO_PIN, OUTPUT); digitalWrite(PING_SENSOR_IO_PIN, LOW); delayMicroseconds(2); digitalWrite(PING_SENSOR_IO_PIN, HIGH); delayMicroseconds(5); digitalWrite(PING_SENSOR_IO_PIN, LOW); pinMode(PING_SENSOR_IO_PIN, INPUT); const unsigned long duration = pulseIn(PING_SENSOR_IO_PIN, HIGH); const unsigned threshold = (microseconds_to_cm(duration)); if (duration == 0) { digitalWrite(LED_PIN, LOW); } else if (threshold <= 35 && threshold >= 21) { blink1(); sonar1(); } else if (threshold <= 20 && threshold >=6) { blink2(); sonar2(); } else if (threshold <=5) { digitalWrite(LED_PIN, HIGH); sonar3(); } else { digitalWrite(LED_PIN, LOW); } delay(100); } unsigned long microseconds_to_cm(const unsigned long microseconds) { return microseconds / 29 / 2; } void blink1() { digitalWrite(LED_PIN, HIGH); delay(200); digitalWrite(LED_PIN, LOW); delay(200); } void blink2() { digitalWrite(LED_PIN, HIGH); delay(50); digitalWrite(LED_PIN, LOW); delay(50); } void sonar1() { // play a note on pin 8 for 200 ms: tone(8, 1047, 200); delay(400); } void sonar2() { // play a note on pin 8 for 200 ms: tone(8, 1047, 200); delay(200); } void sonar3() { // play a note on pin 8 for 200 ms: tone(8, 1047, 200); delay(50); }
Video
No comments:
Post a Comment