I am extremely new to Arduino and electrical engineering, and the project I am attempting involves a ultrasonic sensor. I am using the HC-SR04 with the Elegoo Mega2560 Arduino board. A few days ago I was able to print out the distance correctly with an Arduino library, but after adding a h-bridge, 2 motors, and 2 9-volt batteries, the sensor didn't seem to work properly. I went back to a simple circuit with only the HC-SR04, and the distance readouts were all over the place. No matter what, the distance stayed between 90 and 120, mainly staying in the 110s. These numbers seemed to have no correlation with the actual distance. I even tried to calculate the distance myself in case there was something wrong with the library.
I have the VCC pin on the HC-SR04 connected to the 5v on the Arduino, the GND pin connected to the GND pin on the Arduino, the Trigger pin connected to pin 50 on the Arduino, and the Echo pin on the Arduino connected to pin 52 on the Arduino. The Arduino is connected to my computer through USB.
Here is my sketch for printing out the distance without a library:
const int triggerPIN = 50; //these are digital pins on the Arduino board
const int echoPIN = 52; //I'm sure these pins aren't broken because I never used them before now
long duration;
int distance;
void setup() {
Serial.begin(9600);
pinMode (triggerPIN, OUTPUT);
pinMode (echoPIN, INPUT);
delay(1000);
}
int getDistance () {
digitalWrite (triggerPIN, LOW);
delayMicroseconds (2);
digitalWrite (triggerPIN, HIGH);
delayMicroseconds (10);
digitalWrite (triggerPIN, LOW);
duration = pulseIn (echoPIN, HIGH);
distance = duration * 0.034 / 2;
Serial.println (distance);
}
void loop() {
getDistance (); //I tried putting the code directly in the loop function with the same result
}
I am afraid that I broke either a part of the Arduino board or the sensor when I was fiddling around with the two batteries. Is it possible to break a HCSR04 sensor by connecting two much voltage to the VCC pin on the sensor? If so, how should I prevent this in the future? I know that the working voltage for a HCSR04 is 5V, does this mean it needs at least 5V or no more than 5V? I wanted to know for sure that it was broken and not an error on my part before I bought a new one. Thanks in advance!