I've hooked up two ultrasonic sensors to my breadboard and I also got a 5 V motor installed. I also got the diode installed and the usual set up. I can easily control the motor with one sensor.
I want the motor to run at let's say 100 once I start it up:
- The first sensor should be used to slowly slow down the motor when an object is placed in front of it
- The second sensor should be used to slowly speed up the motor when an object is placed in front of it
I do not want the speed to return to 100 once the object is removed. It should remain at the same speed according to which sensor was used.
Tell me if I have to clarify anything in the comments.
Code
int motorPin = 9;
int trigPin = 13;
int echoPin = 12;
int trigPin2 = 5;
int echoPin2 = 4;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(motorPin, OUTPUT);
}
void loop() {
int duration, distance;
digitalWrite (trigPin, HIGH);
delayMicroseconds (1000);
digitalWrite (trigPin, LOW);
duration = pulseIn (echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance < 20) { // Distance from sensor
analogWrite (motorPin, 50);
} else {
int duration, distance;
digitalWrite (trigPin2, HIGH);
delayMicroseconds (1000);
digitalWrite (trigPin2, LOW);
duration = pulseIn (echoPin2, HIGH);
distance = (duration/2) / 29.1;
if (distance > 20) { // Distance from sensor
analogWrite (motorPin, 150);
}
if (distance > 20) { // Distance from sensor
Serial.println("Out of range");
} else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}
}