EasyManua.ls Logo

SunFounder 3in1 Kit - Page 254

Default Icon
351 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
SunFounder 3in1 Kit
(continued from previous page)
void setup() {
...
//ultrasonic
pinMode(echoPin, INPUT);
pinMode(trigPin, OUTPUT);
}
2. First read the distance value obtained from the ultrasonic module, if the distance is greater than 25, let the car
move forward; if the distance is between 2-10cm, let the car move backward, otherwise (between 10~25) stop.
void loop() {
float distance = readSensorData();
if (distance > 25) {
moveForward(200);
}
else if (distance < 10 && distance > 2) {
moveBackward(200);
} else {
stopMove();
}
}
3. About readSensorData() function.
The transmitter of the ultrasonic module transmits a 10us square wave signal every 2us, and the re-
ceiver receives a high level signal if there is an obstacle within the range. Use the pulseIn() function
to record the time from sending to receiving, divide by the speed of sound 340m/s, and then divide
by 2, the result is the distance between this module and the obstacle with units: cm.
float readSensorData() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
float distance = pulseIn(echoPin, HIGH) / 58.00; //Equivalent to (340m/
˓s*1us)/2
return distance;
}
pulseIn(pin, value)
pin: the number of the Arduino pin on which you want to read the pulse. Allowed data types:
int.
value: type of pulse to read: either HIGH or LOW. Allowed data types: int.
Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for
the pin to go from LOW to HIGH, starts timing, then waits for the pin to go LOW and stops timing.
250 Chapter 5. Car Projects

Related product manuals