For a robotics project I am using HC SRO4s to allow the robot to detect obstacles in it's surroundings. However, when connected to any Arduino Mega 2560 the sensors return the distance as 0. Four of the sensors I have used previously, and five I purchased two days ago. All Arduinos worked previously and work when other sensors are connected to them.
The error can be recreated using this source code:
const int triggerI = 22;
const int echoI = 23;
int distanceI;
long durationI;
void setup() {
pinMode(triggerI, OUTPUT);
pinMode(echoI, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(triggerI, LOW);
delayMicroseconds(2);
digitalWrite(triggerI, HIGH);
delayMicroseconds(10);
digitalWrite(triggerI, LOW);
durationI = pulseIn(echoI, HIGH);
distanceI = durationI * 0.017;
Serial.println(distanceI);
Serial.println(durationI);
}