Hello!
Please, I need help with this code. Im perfectly sure that everything is well connected to the Arduino board.
The code :
#include "NewPing.h"
#define TRIGGER_PIN 3
#define ECHO_PIN 2
#define MAX_DISTANCE 200
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
// Right engine
int motorDer_C=8;
int motorDer_D=9;
//Left engine
int motorIzq_C=10;
int motorIzq_D=11;
int cm; //Variable
void Adelante(){
digitalWrite(motorIzq_C , HIGH);
digitalWrite(motorIzq_D , LOW);
digitalWrite(motorDer_C , HIGH);
digitalWrite(motorDer_D , LOW);
}
void Frenar(){
digitalWrite(motorIzq_C , LOW);
digitalWrite(motorIzq_D , LOW);
digitalWrite(motorDer_C , LOW);
digitalWrite(motorDer_D , LOW);
}
void DoblarI(){ // Turns left
digitalWrite(motorIzq_C , LOW);
digitalWrite(motorIzq_D , HIGH);
digitalWrite(motorDer_C , HIGH);
digitalWrite(motorDer_D , LOW);
}
void setup() {
pinMode(motorIzq_C, OUTPUT);
pinMode(motorIzq_D, OUTPUT);
pinMode(motorDer_C, OUTPUT);
pinMode(motorDer_D, OUTPUT);
Serial.begin (9600);
}
void loop() {
delay(50);
int cm = sonar.ping_cm();
Serial.print("Ping: ");
Serial.print(cm);
Serial.println("cm");
if (cm<=23){
Frenar();
DoblarI();
}
if (cm>23){
Frenar();
Adelante();
}
}
The problem is the following : In the serial monitor, while the distance is lower than 23, the sensor works just fine. But if the distance is bigger than 23 , the sensor goes crazy.
The problem lies on the conditional, not the distance. If I change 23cm for any other, the same thing happens.
Hope you can help, thank you!