Hi,
I’m not that experienced with Arduino and have a question regarding a while loop, at least that is what I believe it is. I am trying to control two linear actuators with an ultrasonic sensor. The actuators (without position indicator) are connected to a motor controller. What I am trying to accomplish, is when an object comes within a 5 cm range of the sensor, the motors will activate for 100 milliseconds and then stop and hold their position until the sensor detects that the object is >= 5 cm’s. When this happens the motors should go back to their original position.
What I am struggling with now is that everything works except for the motors returning to their original position after the sensor detects an object that is >= 5 cm’s. I am almost certain this has something to do with the while loop.
I hope you can help me!
int enA = 5;
int enB = 3;
const int in1 = 8;
const int in2 = 7;
const int in3 = 4;
const int in4 = 2;
const int pingPin = 12;
long previousMillis = 0;
long interval = 1000;
long time;
long startTime = 0;
long microsecondsToCentimeters(long microseconds) {
return microseconds / 29 / 2;
}
void setup() {
// initialize serial communication:
Serial.begin(9600);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enA, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
}
void loop() {
// Variabele cm
long duration, cm;
time = millis();
// Activate
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
// Signal read
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// to cm
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
//send pulse
if (cm < 5) {
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
analogWrite(enA, 255);
analogWrite(enB, 255);
delay(100);
//keep position?
while (cm < 5){
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
analogWrite(enA, 255);
analogWrite(enB, 255);
Serial.read();
if (cm >= 5){
continue;
}
}
}
//Back to original position
else {
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
analogWrite(enA, 255);
analogWrite(enB, 255);
}
}