Hi everyone, I am making this robotic car that can self navigate using an ultrasonic sensor mounted on a servo. In my code, I have "if" statements that check the position of the servo and the distance of the ultrasonic sensor which in return controls the motor's speed. However, this is the part that doesn't work. (This part is in void movement() ). I see all the correct values in the serial monitor so it must be a code thing. Does anyone know why the if statements are not working? (There are no error messages) Thanks
Here is my code:
#include <NewPing.h>
#include <Servo.h>
Servo servo;
#define TRIGGER_PIN 12
#define ECHO_PIN 11
#define MAX_DISTANCE 200
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
int pos = -60;
unsigned int uS = sonar.ping();
int DIS = uS / US_ROUNDTRIP_CM;
int turntime = 0;
int i = 0;
// D5 is LEFT motor
// D3 is RIGHT motor
// 15 degrees is RIGHT!
//120 degrees is LEFT!
void setup()
{
Serial.begin(9600);
pinMode(5, OUTPUT);
pinMode(3, OUTPUT);
servo.attach(9);
}
void loop(){
for (i = 15; i <= 120; i += 1) {
servo.write(i);
pos = servo.read();
Serial.println(pos);
scan();
delay(10);
movement();
}
for (i = 120; i >= 15; i -= 1) {
servo.write(i);
pos = servo.read();
Serial.println(pos);
scan();
delay(10);
movement();
}
}
void scan() {
//delay(300);
unsigned int uS = sonar.ping();
Serial.print("Ping: ");
int DIS = uS / US_ROUNDTRIP_CM;
if (DIS > 30)
{
int DIS = 20;
}
Serial.print(DIS);
Serial.println("cm");
}
void movement() {
if (DIS < 10 and pos < 26.25) {
turntime = 200;
analogWrite(5, 0); analogWrite(3, 0);
delay(200);
analogWrite(5, 0); analogWrite(3, 220);
delay(turntime);
analogWrite(5, 0); analogWrite(3, 0);
}
if (DIS < 10 and pos > 26.25 and pos < 52.5) {
turntime = 100;
analogWrite(5, 0); analogWrite(3, 0);
delay(200);
analogWrite(5, 0); analogWrite(3, 220);
delay(turntime);
analogWrite(5, 0); analogWrite(3, 0);
}
if (DIS < 10 and pos > 52.5 and pos < 78.75){
turntime = 100;
analogWrite(5, 0); analogWrite(3, 0);
delay(200);
analogWrite(5, 0); analogWrite(3, 220);
delay(turntime);
analogWrite(5, 0); analogWrite(3, 0);
}
if (DIS < 10 and pos > 78.75){
turntime = 200;
analogWrite(5, 0); analogWrite(3, 0);
delay(200);
analogWrite(5, 0); analogWrite(3, 220);
delay(turntime);
analogWrite(5, 0); analogWrite(3, 0);
}
else
{
analogWrite(5, 110); analogWrite(3, 85);
}
}