4

I was simply trying to program a buzzer with the ultrasonic HC SR04 and 128x64 OLED display. The buzzer is an active buzzer (3 pin) on a small board. The problem is that, once on, it never stops buzzing. I have used the following code which is working fine except the buzzer.

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define trigPin 9 #define echoPin 8 int buzzer = 12;//the pin of the active buzzer #define OLED_RESET 4 Adafruit_SSD1306 display(OLED_RESET);

void setup() { Serial.begin (9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(buzzer,OUTPUT);//initialize the buzzer pin as an output display.begin(SSD1306_SWITCHCAPVCC, 0x3C); //initialize with the I2C addr 0x3C (128x64) display.clearDisplay();

}

void loop() { float duration; float distance_cm; float distance_in; digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance_cm = (duration/2) / 29.1; //distance_in = (duration/2) / 73.914;

display.setCursor(30,0); //oled display display.setTextSize(1); display.setTextColor(WHITE); display.println("Distance");

display.setCursor(30,10); //oled display display.setTextSize(1); display.setTextColor(WHITE);

if(distance_cm<2.9) { noTone(buzzer); display.println("Too Close");

} else if(distance_cm>30) { noTone(buzzer); display.println("Out of Range");

} else if(distance_cm>2.9 && distance_cm<3.5 ) {

display.println(distance_cm); display.setCursor(80,10); display.setTextSize(1); display.println("cm"); display.setCursor(30,20); //oled display display.setTextSize(1); display.setTextColor(WHITE); display.println("Reading Data"); tone(buzzer,329);
delay(20); noTone(buzzer);
}

else { noTone(buzzer); display.println("Too Far");

}

display.display();

delay(500); display.clearDisplay(); Serial.println(distance_cm);

}

I am a beginner in Arduino programming ( Although have basic knowledge in C and python). You can make any optimization of this code if you feel so. Please help.

enter image description here

Bukaida
  • 141
  • 2

1 Answers1

1

I think that for a passive buzzer you might take ‘noTone(buzzer);’ out of every conditional statement and place it as a default buzzer reset near the beginning of void loop() - at least before the first ‘if’ conditional. The point: move the buzzer state positively off of a silent condition when the right condition is met.

For an active buzzer, as you have, do the suggestion - but use HIGH criterion at pin output statements, and LOW at beginning of loop.

I notice also that there is a distance range not covered in the if/else tests. Not that it must matter.

DLSmith
  • 77
  • 4