Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Connections

...

Code

C++

Blocks

Code Block
languagecpp
themeConfluence
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(
5
leftMotorBwd, OUTPUT);
  pinMode(
6
leftMotorFwd, OUTPUT);
}
 
void loop()
{
  distanceCm = 0.01723 * readUltrasonicDistance(9, 8);
  if (distanceCm > 50) {
    analogWrite(
5
leftMotorBwd, 0);
    analogWrite(
6
leftMotorFwd, fullSpeed);
  } else {
    if (distanceCm > 25) {
      analogWrite(
5
leftMotorBwd, 0);
      analogWrite(
6
leftMotorFwd, quarterSpeed);
    } else {
      if (distanceCm <= 20) {
        analogWrite(
5
leftMotorBwd, quarterSpeed);
        analogWrite(
6
leftMotorFwd, 0);
      } else {
        analogWrite(
5
leftMotorBwd, 0);
        analogWrite(
6
leftMotorFwd, 0);
      }
    }
  }
  delay(200); // Wait for 200 millisecond(s)
}
]] ></ac:plain-text-body></ac:structured-macro></div></td><td><div class="content-wrapper"><p><ac:image ac:width="500"><ri:attachment ri:filename="image2020-1-23_14-10-18.png" /></ac:image></p></div></td></tr></tbody></table><p><br /></p><p><br /></p><p><br /></p>


image2020-1-23_14-10-18.pngImage Added