HC-SR04 rangefinder – Week 4

In our fourth week we had to connect our HC-SR04 rangefinder to our circuit board and program it to pick up an object within 90cm.

We first had to solder wires onto the rangefinder to enable us to connect it to the circuit board. We decided on using black wires for the Vcc and Gnd connection, an orange wire for the Trig connection and a green wire for the Echo connection so it would be easier to identify which wire was which.


Below is the code we wrote to get the HC-SR04 to pick up a object within a 90cm range. We originally used an example code found on robosumo.wordpress.com as a guide to help us build our own code. I also used online resources (eg. https://www.makerguides.com/hc-sr04-arduino-tutorial/ ) to figure out how to convert my desired distance into m/s for my rangefinder. This assisted me in writing the code. I used the distance=speed X time/2 formula to convert 90cm into m/s. For speed i used the units cm/µs which is the speed of sound (0.0343 cm/µs ).

Distance(cm)=speed of sound( cm/µs ) X Time/2 (m/s) [(0.0343cm/µs) / (90cm)] 2 = 5248m/s

// HC-SR04 rangefinder 
// Written by group 31 9-10-2019
void setup()
  pinMode(7, OUTPUT); // trigger
  pinMode(8, INPUT);  // echo
  pinMode(2, OUTPUT); // LED 1 (yellow)
  pinMode(3, OUTPUT); // LED 2 (green)
  pinMode(4, OUTPUT); // LED 3 (blue)
void loop()
  // Send trigger pulse
  digitalWrite(7, HIGH);
  digitalWrite(7, LOW);
  delayMicroseconds(5248); //  5248m/s
  int echoState;
  echoState = digitalRead(8);
  if (echoState == 0)
    // object within 90cm
    digitalWrite(2, HIGH);
    digitalWrite(3, LOW);
    // object is farther than 90cm
    digitalWrite(2, LOW);
    digitalWrite(3, HIGH);
  delay(50); // 50 ms delay to let any ultrasoubnd reflections die away

Above is a video demonstrating our functioning rangefinder. Its programmed so that when it detects an object within a 90cm range the green LED switches to the yellow LED. This can be observed when the purple book is placed in front of the rangefinder.

During this week we also began to build the body of our robot by firstly attaching the motors with insulation tape to the battery. We then made a whatsapp group chat to have more sufficient communication between each other.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s