Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Version History

« Previous Version 6 Next »

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)
}]] ></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>
  • No labels