Hello everyone,
I just received my 4 hc-04 that I had ordered on eBay.
I had written some code to try to get it working.
int trig1 = 22; // attach pin 3 to Trig
int trig2 = 23; // attach pin 23 to Trig
int trig3 = 24; // attach pin 24 to Trig
int trig4 = 25; // attach pin 25 to Trig
int echo1 = 30; //attach pin 30 to Echo
int echo2 = 31; //attach pin 31 to Echo
int echo3 = 32; //attach pin 32 to Echo
int echo4 = 33; //attach pin 33 to Echo
void setup() {
// initialize serial communication:
Serial.begin(9600);
}
void loop()
{
pinMode(echo1,INPUT);
pinMode(echo2,INPUT);
pinMode(echo3,INPUT);
pinMode(echo4,INPUT);
pinMode(trig1, OUTPUT);
pinMode(trig2, OUTPUT);
pinMode(trig3, OUTPUT);
pinMode(trig4, OUTPUT);
long duration1, cm1;
long duration2, cm2;
long duration3, cm3;
long duration4, cm4;
/*
//TEST ONLY DO NOT ENABLE
pinMode(trig1, OUTPUT);
pinMode(trig2, OUTPUT);
pinMode(trig3, OUTPUT);
pinMode(trig4, OUTPUT);
digitalWrite(trig1, LOW);
digitalWrite(trig2, LOW);
digitalWrite(trig3, LOW);
digitalWrite(trig4, LOW);
delayMicroseconds(2);
digitalWrite(trig1, HIGH);
digitalWrite(trig2, HIGH);
digitalWrite(trig3, HIGH);
digitalWrite(trig4, HIGH);
delayMicroseconds(5);
digitalWrite(trig1, LOW);
digitalWrite(trig2, LOW);
digitalWrite(trig3, LOW);
digitalWrite(trig4, LOW);
*/
digitalWrite(trig1, LOW);
delayMicroseconds(2);
digitalWrite(trig1, HIGH);
delayMicroseconds(5);
digitalWrite(trig1, LOW);
duration1 = pulseIn(echo1, HIGH);
delayMicroseconds(9000);
digitalWrite(trig2, LOW);
delayMicroseconds(2);
digitalWrite(trig2, HIGH);
delayMicroseconds(5);
digitalWrite(trig2, LOW);
duration2 = pulseIn(echo2, HIGH);
delayMicroseconds(9000);
digitalWrite(trig3, LOW);
delayMicroseconds(2);
digitalWrite(trig3, HIGH);
delayMicroseconds(5);
digitalWrite(trig3, LOW);
duration3 = pulseIn(echo3, HIGH);
delayMicroseconds(9000);
digitalWrite(trig4, LOW);
delayMicroseconds(2);
digitalWrite(trig4, HIGH);
delayMicroseconds(5);
digitalWrite(trig4, LOW);
duration4 = pulseIn(echo4, HIGH);
delayMicroseconds(9000);
// convert the time into a distance
cm1 = microsecondsToCentimeters(duration1);
cm2 = microsecondsToCentimeters(duration2);
cm3 = microsecondsToCentimeters(duration3);
cm4 = microsecondsToCentimeters(duration4);
Serial.print(cm1);
Serial.print(" cm for NO1");
Serial.println();
Serial.print(cm2);
Serial.print(" cm for NO2");
Serial.println();
Serial.print(cm3);
Serial.print(" cm for NO3");
Serial.println();
Serial.print(cm4);
Serial.print(" cm for NO4");
Serial.println();
delay(100);
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
but I can only seem to get 1 and 3 to work and the others return an 0 cm
Any help will be appreciated.
BTW I am using an Arduino Mega clone and this module has 4 pins
Yours Faithfully,
12458