Hello guys! I am a student and I am a noob with Arduino.
I use a Arduino mega 2560 with a L298N Motor Drive Shield and one ultrasonic sensor(HC-SR04)
I just can’t use the ultrasonic sensor to control my motor, I really don’t have any ideas why it doesn’t work
What I want to do is that, I want the motor turn to different sides(both left and right) when it is out of the range(data from ultrasonic)
so that it can balance the robot.
Here’s my code:
const int M1 = 0; // direction motor 1
const int M2 = 2; // direction motor 2
const int M1BRAKE = 1; // pwm motor 1
const int M2BRAKE = 3; // pwm motor 2
#define trigPin 9
#define echoPin 8
long duration,distance;
void setup() {
Serial.begin(9600);
pinMode(0, OUTPUT); // direction motor 1, left front
pinMode(2, OUTPUT); // direction motor 2, left rear
pinMode(1, OUTPUT); // motor 1 BRAKE
pinMode(3, OUTPUT); // motor 2 BRAKE
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
int val = analogRead(echoPin);
if(val>=10 && val<=50){
digitalWrite(M1, HIGH);
digitalWrite(M2, HIGH);
digitalWrite( M1BRAKE,LOW);
digitalWrite( M2BRAKE,LOW);
}else if(val>=100){
digitalWrite( M1BRAKE,HIGH);
digitalWrite( M2BRAKE,HIGH);
digitalWrite(M1, LOW);
digitalWrite(M2, LOW);
}else if (val>=5){
digitalWrite( M1BRAKE,LOW);
digitalWrite( M2BRAKE,LOW);
digitalWrite(M1, LOW);
digitalWrite(M2, LOW);
}
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
Serial.print(distance);
Serial.println(“cm”);
//Delay 50ms before next reading.
delay(50);
I am pressing to look for your suggestions, thank you!