Hi everyone.
Let me go straight into the problem: I have been writing a code to control a dc motor using two ultrasonic sensors 1 & 2 measuring distance1 and distrance2 respectively.
- As the motor is moving forward the distance1 is increasing from 95 cm until it is zero (out or range).
- Whilst the motor is moving forward, the distance2 is also increasing from 28 cm up 41 cm. The distance2 defines my upper limit and lower limits for the operation of the motor.
- i want the motor to immediately reverse as distance1 is out of range. The following code i have been using does not reverse.
House please help out with fixing my codes below so the motor reverse back when the distance1 is out of range and stops when the upper limit is 39 cm:
#include <NewPing.h>
#define TRIG_PIN1 4
#define ECHO_PIN1 5
#define TRIG_PIN2 9
#define ECHO_PIN2 10
#define MAX_DISTANCE 200
NewPing sonar1(TRIG_PIN1, ECHO_PIN1, MAX_DISTANCE);
NewPing sonar2(TRIG_PIN2, ECHO_PIN2, MAX_DISTANCE);
int CRD_REFERENCE = 107; // Define CRD_REFERENCE
int CRD_HEIGHT = 0; // Initialize CRD_HEIGHT with a default value
const float US_upper_limit = 41.0;
const float US_lower_limit = 29.0;
#define RPWM 11
#define LPWM 12
void setup() {
Serial.begin(9600); // Start serial communication
pinMode(RPWM, OUTPUT);
pinMode(LPWM, OUTPUT);
// Stop motors
analogWrite(RPWM, 0);
analogWrite(LPWM, 0);
}
void loop() {
// Trigger the first sensor
unsigned int distance1 = sonar1.ping_cm();
Serial.print("Distance1: ");
Serial.print(distance1);
Serial.println(" cm");
// Trigger the second sensor
unsigned int distance2 = sonar2.ping_cm();
Serial.print("Distance2: ");
Serial.print(distance2);
Serial.println(" cm");
delay(1000); // Wait for 1 second before taking another reading
// Check conditions for DEFLECTOR_UP
if (distance1 >= 95 ) {
// if (distance1 >= 95 && distance2 < US_upper_limit) {
// Accelerate forward
digitalWrite(RPWM, LOW);
for (int i = 0; i < 255; i++) {
analogWrite(LPWM, i);
delay(20);
}
// Decelerate forward
for (int i = 255; i >= 0; i--) {
analogWrite(LPWM, i);
delay(20);
}
CRD_HEIGHT = distance1; // Assuming CRD_HEIGHT is a global variable
} else { // Reverse when distance2 exceeds the upper limit
//else if (distance2 > US_upper_limit) { // Reverse when distance2 exceeds the upper limit
// Accelerate reverse
digitalWrite(LPWM, LOW);
for (int i = 0; i < 255; i++) {
analogWrite(RPWM, i);
}
// Decelerate reverse
for (int i = 255; i >= 0; i--) {
analogWrite(RPWM, i);
}
delay(500);
} if (CRD_REFERENCE == (CRD_HEIGHT - 10)) { // Note the use of '==' instead of '='
}
else {
// Stop motors
analogWrite(RPWM, 0);
analogWrite(LPWM, 0);
delay(2000);
}
// Finding Trailer Height
//if (CRD_REFERENCE == (CRD_HEIGHT - 10)) { // Note the use of '==' instead of '='
CRD_REFERENCE = CRD_HEIGHT;
}
I look forward to receiving any help.
Regards,
Baba