/
Exercise 4 Solution
Exercise 4 Solution
Connections
Code
C++ | Blocks |
---|---|
int distanceCm = 0;
/* using variables / identifiers instead of hard-coded values
makes the code more readable and easier to modify */
int quarterSpeed = 64;
int fullSpeed = 255;
/* the following names assume a scenario where
left motor is controlled*/
int leftMotorFwd = 6;
int leftMotorBwd = 5;
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
/* Reads the echo pin, and returns the sound wave
travel time in microseconds */
return pulseIn(echoPin, HIGH);
}
void setup()
{
pinMode(leftMotorBwd, OUTPUT);
pinMode(leftMotorFwd, OUTPUT);
}
void loop()
{
distanceCm = 0.01723 * readUltrasonicDistance(9, 8);
if (distanceCm > 50) {
analogWrite(leftMotorBwd, 0);
analogWrite(leftMotorFwd, fullSpeed);
} else {
if (distanceCm > 25) {
analogWrite(leftMotorBwd, 0);
analogWrite(leftMotorFwd, quarterSpeed);
} else {
if (distanceCm <= 20) {
analogWrite(leftMotorBwd, quarterSpeed);
analogWrite(leftMotorFwd, 0);
} else {
analogWrite(leftMotorBwd, 0);
analogWrite(leftMotorFwd, 0);
}
}
}
delay(200); // Wait for 200 millisecond(s)
} |
|