Skip to content

Instantly share code, notes, and snippets.

@gkgkgkgk
Created July 3, 2020 19:48
#define enA 3 //enable pin of motor a
#define in1 8 // left pin of motor a
#define in2 7 // right pin of motor a
#define enB 5
#define in3 6
#define in4 4
#define trigPin 12
#define echoPin 13
int motorSpeedA = 0;
int motorSpeedB = 0;
long duration;
int distance;
void setup() {
// put your setup code here, to run once:
pinMode(enA, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Begin Serial communication at a baudrate of 9600:
Serial.begin(9600);
}
void loop() {
// clear the trigPin by setting it LOW:
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
// Trigger the sensor by setting the trigPin high for 10 microseconds:
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
//Read the echoPin, pulseIn() returns the duration in microseconds:
duration = pulseIn(echoPin, HIGH);
//Calculate the distance:
distance = duration*0.034/2;
//Print the distance on the Serial Monitor (Ctrl+Shift+M)
Serial.print("Distance = ");
Serial.print(distance);
Serial.println("cm");
if (distance < 10) {
digitalWrite(in1, HIGH); // turn left pin of motor a to high
digitalWrite(in2, LOW); // turn right pin of motor a to high
analogWrite(enA, 150); // set speed of motor A
digitalWrite(in3, LOW); // turn left pin of motor b to low
digitalWrite(in4, HIGH); // turn right pin of motor b to high
analogWrite(enB, 150); // set speed of motor B
}
else {
digitalWrite(in1, HIGH); // turn left pin of motor a to high
digitalWrite(in2, LOW); // turn right pin of motor a to low
analogWrite(enA, 150); // set speed of motor A
digitalWrite(in3, HIGH); // turn left pin of motor b to high
digitalWrite(in4, LOW); // turn right pin of motor b to low
analogWrite(enB, 150); // set speed of motor B
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment