2

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

3
  • Comments are not for extended discussion; this conversation has been moved to chat.
    – Juraj
    Sep 13, 2021 at 10:43
  • Temporarily solved by replacing the active buzzer with a 2 pin passive buzzer. the behavior of the active buzzer remained mysterious to me.
    – Bukaida
    Sep 13, 2021 at 11:02
  • 2
    often they are high to silence.
    – dandavis
    Sep 13, 2021 at 19:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.