When I wrote the code to turn on the engine, the sensor itself does not work, and when I directly connected the battery to the engine, everything works. I used Sharp GP2Y0A02YK0F encoder and servo motor to rotate the motor. And here is the code itself
Blockquote
#include <SharpIR.h>
#include <Servo.h>
#include <G2MotorDriver.h>
#define sensorIR A0
#define model 20150
float sensorValue, cm;
#define DIR 4
#define PWM_Motor 5
int dis;
Servo servo;
SharpIR sensor = SharpIR(sensorIR, model);
void setup() {
servo.attach(9);
Serial.begin(9600);
pinMode(DIR, OUTPUT);
pinMode(PWM_Motor, OUTPUT);
}
void loop() {
dis = sensor.distance();
sensorValue = analogRead(sensorIR);
cm = 10650.08 * pow(sensorValue,-0.935) - 10;
delay(100); //read sensor
servo.write(145);
if(dis<70){ //compare to threshold
for (int i = 120; i >= 0; i–){
analogWrite(PWM_Motor, i);
digitalWrite(PWM_Motor, LOW);
digitalWrite(PWM_Motor, HIGH);
digitalWrite(DIR, LOW);
servo.write(145);
}
}else{
for (int i = 50; i < 120; i++){
analogWrite(PWM_Motor, i);
digitalWrite(PWM_Motor, HIGH);
digitalWrite(PWM_Motor, LOW);
digitalWrite(DIR, HIGH);
servo.write(175);
}
}
}