Using the Ultrasonic Module

Adding the Ultrasonic Module to the Robot 

Start by inserting the ultrasonic module into the robot as shown in the photo below.

Your robot should look similar to the one in the photo below.

Ultrasonic Module in placeUltrasonic Module in place

The ultrasonic module (as discussed in the previous section) can be used to measure distances. We'll start with a very basic Arduino sketch from the NewPing library that prints the distance detected to the serial monitor.

Programming the Ultrasonic Module 

Make sure you install the NewPing library using Arduino's library manager. If you have not done this before, visit Arduino's library manager guide to see how. NOTE: NewPing may not yet be listed in the Arduino library manager. You can download the library zip file here.

Once you have installed the library (and restarted the Arduino IDE, if necessary), you can access this example code from the Arduino IDE by clicking on the File menu. File > Examples > NewPing > NewPingExample. Note, however, that you must adjust the pin definitions to map to the layout of the WiFi Bot PCB. These definitions are shown in the code below.

Download file Copy to clipboard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define TRIGGER_PIN  10  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     7   // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
}

Open the Serial monitor (as shown in the images below) and check to see a similar output.

The code below will provide you a hint if you need it. This code will make the robot stop moving if it detects an obstacle within 10cm. This works by intrdoucing a Boolean obstacleDetected . Booleans are variables that can have one of two values: true or false. We initialize the variable obstacleDetected to false and then check it each time we set the motors to move. In the loop() function, we update this variable based on the distance value calculated from the ultrasonic module.

Download file Copy to clipboard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#include <NewPing.h>

#define TRIGGER_PIN  10
#define ECHO_PIN     7
#define MAX_DISTANCE 200

// Boolean (True or False) variable to control whether or not
// the motors move
bool obstacleDetected = false;

// Sonar object (ultrasonic module)
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

// Pin assignments
#define AIN1 3
#define AIN2 4
#define APWM 5
#define BIN1 12
#define BIN2 13
#define BPWM 11
#define STBY 6


// Constants for motor control functions
#define STEPTIME 600 
#define STRAIGHTSPEED 200
#define TURNSPEED 120
#define TURNTIME 300

// Array to track current PWM values for each channel (A and B)
int pwms[] = {APWM, BPWM};

// Offsets to be used to compensate for one motor being more powerful
byte leftOffset = 0;
byte rightOffset = 0;

// Variable to track remaining time
unsigned long pwmTimeout = 0;

// Function to write out pwm values
void writePwms(int left, int right){
    analogWrite(pwms[0], left);
    analogWrite(pwms[1], right);
}

// Move the robot forward for STEPTIME
void goForward(){
    // If an obstacle was detected, stop
    if(obstacleDetected){
        stop();
    } else {
        // Otherwise, advance
        digitalWrite(STBY, HIGH);
        digitalWrite(AIN1, LOW);
        digitalWrite(AIN2, HIGH);
        digitalWrite(BIN1, LOW);
        digitalWrite(BIN2, HIGH);
        writePwms (STRAIGHTSPEED-leftOffset,STRAIGHTSPEED-rightOffset);
        pwmTimeout = millis() + STEPTIME;
    }
}

// Move the robot backward for STEPTIME
void goBack(){
    // If an obstacle was detected, stop
    if(obstacleDetected){
        stop();
    } else {
        // Otherwise, advance
        digitalWrite(STBY, HIGH);
        digitalWrite(AIN1, HIGH);
        digitalWrite(AIN2, LOW);
        digitalWrite(BIN1, HIGH);
        digitalWrite(BIN2, LOW);
        writePwms (STRAIGHTSPEED-leftOffset,STRAIGHTSPEED-rightOffset);
        pwmTimeout = millis() + STEPTIME;
    }
}

// Turn the robot left for TURNTIME
void goLeft(){
    // If an obstacle was detected, stop
    if(obstacleDetected){
        stop();
    } else {
        // Otherwise, advance
        digitalWrite(STBY, HIGH);
        digitalWrite(AIN1, HIGH);
        digitalWrite(AIN2, LOW);
        digitalWrite(BIN1, LOW);
        digitalWrite(BIN2, HIGH);

        writePwms (TURNSPEED,TURNSPEED);
        pwmTimeout = millis() + TURNTIME;
    }
}

// Turn the robot right for TURNTIME
void goRight(){
    // If an obstacle was detected, stop
    if(obstacleDetected){
        stop();
    } else {
        digitalWrite(STBY, HIGH);
        digitalWrite(AIN1, LOW);
        digitalWrite(AIN2, HIGH);
        digitalWrite(BIN1, HIGH);
        digitalWrite(BIN2, LOW);

        writePwms (TURNSPEED,TURNSPEED);
        pwmTimeout = millis() + TURNTIME;
    }
}

// Stop the robot (using standby)
void stop(){
    digitalWrite(STBY, LOW); 
}

// Arduino setup function
void setup(){
    // Initialize pins as outputs
    pinMode (STBY, OUTPUT);
    pinMode (AIN1, OUTPUT);
    pinMode (AIN2, OUTPUT);
    pinMode (APWM, OUTPUT);
    pinMode (BIN1, OUTPUT);
    pinMode (BIN2, OUTPUT);
    pinMode (BPWM, OUTPUT);
    pinMode (TRIGGER_PIN, OUTPUT);
    pinMode (ECHO_PIN, INPUT);
    Serial.begin(115200);
}

// Loop (code betwen {}'s repeats over and over again)
void loop(){

    // Trigger ultrasonic ping
    int uS = sonar.ping();
    // Calculate distance in cm
    int distance = uS / US_ROUNDTRIP_CM;
    Serial.print("Ping: ");
    Serial.print(distance);
    Serial.println("cm");

    // If there is an object within 10cm of the sensor
    // NOTE: The NewPing library returns 0 if no object is detected.
    if(distance <= 10 && distance != 0){
        // Set the obstacleDetected flag to disable the motors
        obstacleDetected = true;
    }

    // Make the robot go Forward.
    goForward();
    // Wait for one second
    delay(1000);
    // Make the robot stop
    stop();
    // Wait for one second
    delay(1000);
    // Make the robot go backward
    goBack();
    // Wait for one second
    delay(1000);
    // Make the robot stop
    stop();
    // Wait for one second
    delay(1000);
}