int motorPin = 9;
int trigPin = 13;
int echoPin = 12;
int trigPin2 = 5;
int echoPin2 = 4;
int postdist = 112;
int postdist2 = 112;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(motorPin, OUTPUT);
}
void loop() {
//First Read
int duration, distance;
digitalWrite (trigPin, HIGH);
delayMicroseconds (1000);
digitalWrite (trigPin, LOW);
duration = pulseIn (echoPin, HIGH);
distance = (duration/2) / 29.1;
int ltol = postdist - 5;
int htol = postdist + 5;
if (distance > 20 || !(distance > ltol && distance < htol)) { // Distance from sensor
Serial.println("Out of range");
distance = postdist;
}
//Second Read
int duration2, distance2;
digitalWrite (trigPin2, HIGH);
delayMicroseconds (1000);
digitalWrite (trigPin2, LOW);
duration2 = pulseIn (echoPin2, HIGH);
distance2 = (duration2/2) / 29.1;
int ltol2 = postdist2 - 5;
int htol2 = postdist2 + 5;
if (distance2 > 20 || !(distance2 > ltol2 && distance2 < htol2)) { // Distance from sensor
Serial.println("Out of range");
distance2 = postdist2;
}
//Math:
Serial.print("Distances-1: ");
Serial.print(distance);
Serial.print(" cm 2: ");
Serial.print("Distances-1: ");
Serial.print(distance2);
Serial.println(" cm");
postdist = distance;
postdist2 = distance2;
int speed = 112 + map(distance, 0, 20, 0, 112) - map(distance2, 0, 20, 0, 112);
if(speed < 60) {speed = 60;} //Modify 60 to meet your needs for minimum threshold
analogWrite (motorPin, speed);
Serial.print("Motor Speed: ");
Serial.println(speed);
delay(500);
}
Changelog: forgot to edit postdist
/postdist2
at end of cycle, added minimum threshold, prevent very small changes in voltage to keep voltage stable and prevent noise.