1

I wanted to make a buzzer go off when the distance measured by the ultrasonic sensor becomes more than 100cm. The things used in this project are a 4x4 keypad, an hc-sr04 ultrasonic sensor, and a passive buzzer all connected to a keyestudio mega 2560.

What happens is that the moment I upload the code/turn on the Arduino, the buzzer turns on despite a solid object being within a 100cm range. And the buzzer almost randomly stops for a couple of seconds and continues. It won't turn off, even when I press the appropriate key on the keypad.

This is the code I have written, thanks

    #include <Key.h>
    #include <Keypad.h>

    const int trigPin = 11;    //output to sensor
    const int echoPin = 12;    //input from sensor
    const int buzzPin = 13;    //output to buzzer

    const byte ROWS = 4;
    const byte COLS = 4;

    long duration;    //travel time of sound waves
    int distance;    //distance at which an object is

    char hexaKeys[ROWS][COLS] = {
      {'1', '2', '3', 'A'},
      {'4', '5', '6', 'B'},
      {'7', '8', '9', 'C'},
      {'*', '0', '#', 'D'}
    };

    byte rowPins[ROWS] = {9,8,7,6};
    byte colPins[COLS] = {5,4,3,2};

    Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

    void setup() {
      // put your setup code here, to run once:
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(buzzPin, OUTPUT);
      Serial.begin(9600);
    } 

    void loop() {
      // put your main code here, to run repeatedly:

      char customKey = customKeypad.getKey(); // gets key values from keypad

      if(customKey) {
        Serial.println(customKey);
       }

      digitalWrite(trigPin, LOW);    //reset the sensor by turning it off for 2 microseconds
      delayMicroseconds(5);

      digitalWrite(trigPin, HIGH);    //generate ultrasound wave by turning it on for 10 microseconds
      delayMicroseconds(50);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);    //time it takes for sound to get back
      distance = duration*0.034/2;    //plug into formula for distance

      Serial.println(distance);

    if (distance <= 100){
     digitalWrite(buzzPin, LOW);
      }
    if (distance >= 100){ 
      digitalWrite(buzzPin, HIGH);
      if (customKey != 7){
        digitalWrite(buzzPin, HIGH);
        delay(2000);
        digitalWrite(buzzPin, LOW);
        delay(1000);
      if (customKey == 7){
        digitalWrite(buzzPin, LOW);
}
}
}
 }
2
  • 1
    indent the braces at the end of your program properly ... you may notice that they are in the wrong places
    – jsotola
    Nov 11 '20 at 1:58
  • what is printing in serial monitor?
    – jsotola
    Nov 11 '20 at 2:38

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.