Distance sensor

Technical specifications

  • Model: HC-SR04
  • Supply voltage: 5.0 V
  • Operating current: 15 mA
  • Operating frequency: 40 kHz
  • Operating angle: 15 degrees

The sensor measures distance to objects using ultrasound. It is useful for measuring distances in maze competitions and research projects.

How it works: The sensor emits 40 kHz sound pulses and listens for the echo. The time taken for the sound wave to travel to an object and back indicates its distance. The maximum measurable distance is 300 cm.

Connection

The sensor uses a standard 3-pin connector and connects to any IN port on Trackduino.

SensorController (IN)
Vcc+
Gnd−
Trig or EchoS

Gnd is the negative power contact (ground); Vcc is the positive power contact. Trig and Echo use the digital signal (S) contact.

Programming

The required blocks are in the “Sensors” block group.

Block and generated functionDescription
Distance measurement block
int distanceCM(int port)
Returns a value from 2 to 300 corresponding to the measured distance in centimeters.

Argument: int port — the port the sensor is connected to.

Project example

Stop a two-motor cart at a set distance

Generated code:

void setup()
{
}

void loop()
{
  if (( ( distanceCM( IN1 ) ) > ( 20 ) ))
  {
    startMotor(1, 40);
    startMotor(2, 40);
  }
  else
  {
    stopMotor(1);
    stopMotor(2);
    stopProgram();
  }
}

The ultrasonic sensor has been updated. Earlier, echoes from previous measurements could cause unstable readings at short distances (around 20–30 cm). The sensor library was adjusted to make measurements more stable and the conversion coefficient was corrected so the distance is closer to the actual value. A reading of 300 in non-ideal conditions is normal; it is an error code indicating that no valid echo was received, not a distance.