Hi ,
So I'm working on this bot which does waste segregation. Part of the project depends upon the distance between a wall placed in front and the bot itself to locate the right bins. So, for testing the sensor , I uploaded a code from online and connected the pins as following.
HC-SR04 ----- ARDUINO
VCC 5v
GND GND
TRIG 2
ECHO 4
The code is the following.
const int trigPin = 2;
const int echoPin = 4;
void setup() {
Serial.begin(9600);}
void loop()
{
long duration, inches, cm;
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
long microsecondsToInches(long microseconds)
{return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{return microseconds / 29 / 2;}
I've tested out 2 of these sensors on 2 different arduino UNO boards. Though one of these boards was connected to an L293DNE IC , the other one wasn't and I doubt that the IC would make any difference in the operation of the sensor. I first suspected an issue in the jumpers and replaced them with 4 new ones but that didn't resolve the issue. Then , I spotted out the 'pinMode' to be inside the void loop and did some more changes to the code hoping it would resolve my issue but didn't.
const int trigPin = 2;
const int echoPin = 4;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);}
void loop()
{
long duration, inches, cm;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
duration = pulseIn(echoPin, HIGH);
digitalWrite(trigPin, LOW);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
long microsecondsToInches(long microseconds)
{return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{return microseconds / 29 / 2;}
Beside that , there seemed to be no complaints in the comments section of the tutorial I referred to for the code and assumed it to be flawless and its highly unlikely that both my ultrasonic sensors don't work since one of them was a recent purchase.I've also used these before and I never came across such an issue. I also tried connecting the VCC pin to 3V3 rather than 5V but that didn't seem to help either. Now , I'm really confused on how to proceed further and hope to seek some guidance into resolving this incomprehensible issue. I hope this much details is enough.
Thank you ![]()