I need some help with my sensors

I'm working with sensor's and I'm trying to figure out how to activate a buzzer once the sensor detects a certain distance. For some reason the buzzer isn't activating. I attached a picture of my project and here's my code. Please let me know if you find a solution.


#include <LiquidCrystal.h> // includes the LiquidCrystal Library
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)
const int trigPin = 9;
const int echoPin = 10;
long duration;
int distanceCm, distanceInch;

void setup() {
lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
void loop() {
digitalWrite(trigPin, LOW);
digitalWrite(trigPin, HIGH);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distanceCm= duration0.034/2;
distanceInch = duration
lcd.setCursor(0,0); // Sets the location at which subsequent text written to the LCD will be displayed
lcd.print("Distance: "); // Prints string "Distance" on the LCD
lcd.print(distanceCm); // Prints the distance value from the sensor
lcd.print(" cm");
lcd.print("Distance: ");
lcd.print(" inch");
if (distanceInch<15);
tone(50, 51);

NOTE: It is sample code and I modified it. NOT MY CODE!

tone(pin, frequency)
tone(pin, frequency, duration)

“tone(50, 51);”

I don’t believe you can hear 51 hertz.

If that’s a UNO, there is no digital pin 50.

Show us a good schematic of your circuit.
Show us a good image of your ‘actual’ wiring.
Give links to components.

Lose the semi-colon (;) at the end of the if statement. With the semi-colon there the code after the if will execute unconditionally. I recommend using curly brackets to enclose the code after an if even if it is just one line.

if (distanceInch<15)  // removed semi-colon
    tone(pin, frequency);

LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

You should not use pin 1 for the LCD. It is the hardware serial TX pin. I know that your code does not use the serial port but it is likely that in the future you will need the serial port for debugging. The serial port is your best debugging tool.

long duration;
Variables that deal with time should be unsigned long.

Read the forum guidelines to see how to properly post code.
Use the IDE autoformat tool (ctrl-t or Tools, Auto format) before posting code in code tags.

That's used for (piezo) speakers.
You seem to have an active buzzer, that just needs a HIGH/LOW from an output pin.

Try try powering the buzzer directly with 5volt.
Does it make a sound then?

This worked thanks!

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.