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 &lt;= 100){
 digitalWrite(buzzPin, LOW);
  }
if (distance &gt;= 100){ 
  digitalWrite(buzzPin, HIGH);
  if (customKey != 7){
    digitalWrite(buzzPin, HIGH);
    delay(2000);
    digitalWrite(buzzPin, LOW);
    delay(1000);
  if (customKey == 7){
    digitalWrite(buzzPin, LOW);

} } } }

Abhi
  • 31
  • 2

0 Answers0