Arduino robot kit – Range sensor

Ultrasonic Range Sensor and Servo Motor

Ultrasonic Range Sensor and Servo Motor

The robot kit includes an ultrasonic range sensor (HC-SR04), a 2kg-torque servo motor (TowerPro SG90), and a plastic holder that is supposed to attach the motor to the robot top plate and provide a base to attach the sensor. Unfortunately, the items are not totally compatible with each other, so I had to use some wires and widen some holes with a drill to make everything fit together, as shown in the picture.

I used the standard sketch Knob to test the servo motor using the same pin assignment as the sketch.  My servo comes with brown, orange, and yellow wires that correspond to Ground, VCC, and Signal, respectively, so all I had to do is attach the 3-pin female header to the corresponding column of male pins in the sensor shield. Later, I may need to change the pin assignment to be able to use other components.

As for the range sensor, I’ve downloaded the library created by ITead Studio and used its demo to test the sensor, but I had to modify the code to send the output to the serial monitor instead of an LCD. Here is my modified code:

#include "Ultrasonic.h"
Ultrasonic ultrasonic(12,13);

void setup() {
   Serial.begin(9600);
}

void loop() {
   Serial.print(ultrasonic.Ranging(CM));
   Serial.println(" cm");
   delay(100);
}

Range Sweep

The servo motor can be used to move the sensor 180 degrees, while the sensor measures distance at specific angle steps. The range sweep will provide the robot with a view of the distances ahead.

The code snippet below shows that the sensor is rotated 180 degrees twice in each direction and the readings from each direction are averaged to get a better estimate of the distance. Two important things to mention here: First, some time must be allowed after the write()  command before reading the senor to ensure the motor reached the position. The speed of the servo is 5ms/degree but example below allows for 10ms/degree to be sure. Second, the time it takes for ultrasonic.ranging(CM) command to return value depends on the distance of the objects ahead. Therefore, you may notice that while the sensor is rotating, it slows down when there are empty spaces ahead.

void rangeSweep(int st, int en, int dist[]) {
  int pos = 0;
  for(pos = st; pos < en; pos+=STEP) {
    myservo.write(pos); 
    delay(rDelay);
    dist[int(pos/STEP)] = ultrasonic.Ranging(CM);
  }
  for(pos = en; pos > st; pos-=STEP) {                                
    myservo.write(pos);
    delay(rDelay); 
    dist[int(pos/STEP)] += ultrasonic.Ranging(CM);
    dist[int(pos/STEP)] /= 2;
  }
}

To download the complete RangeSweep code click here.