I am trying to build a robot using 2 motors (6V 250 Rpm DC Motor), 2 ultrasonic sensors (HC-SR04 Arduino Ultrasonic Distance Sensor), 1 Arduino (Arduino Uno R3), and 1 motor shield (L293D Motor Driver Shield). I used the map function to control each motor with an ultrasonic sensor. I've printed the datas from the ultrasonic sensors and the speed values from the map functions, and everything seems fine. However, only one of the motors (motor1) is working. The other motor, which was coded the same way, isn't responding no matter what I do.
I noticed that when I removed the sensor-related part of the code, both motors worked without any issues. (I also tried running the motors independently with separate code and different motor inputs, and they all worked flawlessly. Based on this, I believe there's no issue with the input ports, motors, or cables.)
I attempted rewriting the code from scratch for a single motor and a single ultrasonic sensor. The motor worked perfectly fine, but unexpectedly, the other ultrasonic sensor that I didn't even define in the code for this project was somehow affecting the motor's operation. I had soldered the ultrasonic sensors onto the motor shield, so I can't remove them easily. Upon inspecting the connections, there seems to be no physical contact between them.
I still haven't been able to figure out what the problem is. I'm waiting your assistance.
here is my code which 2 ultrasonic sensors and 2 motors:
//-----------------------------------Library
#include <AFMotor.h>
//-----------------------------------Define
#define trigPin1 5
#define echoPin1 3
#define trigPin2 9
#define echoPin2 6
AF_DCMotor motor(1);
AF_DCMotor motortwo(4);
long duration1, duration2, Rightsensor, Leftsensor;
uint8_t i, j;
//-----------------------------------Setup
void setup() {
Serial.begin(9600);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
motor.run(RELEASE);
motortwo.run(RELEASE);
}
//-----------------------------------MAIN LOOP
void loop() {
//SERIAL PRINT
Serial.print(Rightsensor);
Serial.print(" - ");
Serial.print(Leftsensor);
Serial.print(" ");
Serial.print(i);
Serial.print(" - ");
Serial.println(j);
motor.run(FORWARD);
motortwo.run(FORWARD);
motor.setSpeed(distance1());
motortwo.setSpeed(distance2());
delay(250);
}
uint8_t distance1() {
digitalWrite(trigPin1, LOW);
delayMicroseconds(2);
digitalWrite(trigPin1, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin1, LOW);
duration1 = pulseIn(echoPin1, HIGH);
Rightsensor = (duration1 * 0.0343) / 2;
i = map(Rightsensor, 0, 500, 255, 0);
return (i);
}
uint8_t distance2() {
digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
duration2 = pulseIn(echoPin2, HIGH);
Leftsensor = (duration2 * 0.0343) / 2;
j = map(Leftsensor, 0, 500, 255, 0);
return (j);
}