Hello to everyone.I have make a robot that avoid obstacles with the sharp sensor.I upload the code on the Arduino and it doesn't work as expected.The sensor doesn't respond when i place my hand in front of it.The sensor is not damaged.Please if anyone can help me.Thanks in advance.
I want to work like this:
#include <Servo.h>
int const PWMA = 6;
int const PWMB = 5;
int const dirA = 7;
int const dirB = 4;
int servopin = 7;
int sensorpin = 0;
int dist = 0;
int i = 0;
Servo myservo;
int pos = 0;
int A = 0;
int select = 0;
void setup () {
Serial.begin(9600);
myservo.attach(7);
pinMode(PWMA, OUTPUT);
pinMode(PWMB, OUTPUT);
pinMode(dirA, OUTPUT);
pinMode(dirB, OUTPUT);
Serial.println("Robot initialize");
}
void Forward() {
analogWrite(PWMA, 255);
analogWrite(PWMB, 255);
digitalWrite(dirA, HIGH);
digitalWrite(dirB, HIGH);
delay(50);
}
void Backward() {
analogWrite(PWMA, 255);
analogWrite(PWMB, 255);
digitalWrite(dirA, LOW);
digitalWrite(dirB, LOW);
delay(50);
}
void right() {
analogWrite(PWMA, 255);
analogWrite(PWMB, 255);
digitalWrite(dirA, HIGH);
digitalWrite(dirB, LOW);
delay(50);
}
void left() {
analogWrite(PWMA, 255);
analogWrite(PWMB, 255);
digitalWrite(dirA, LOW);
digitalWrite(dirB, HIGH);
delay(50);
}
void STOP() {
analogWrite(PWMA, 0);
analogWrite(PWMB, 0);
digitalWrite(dirA, 0);
digitalWrite(dirB, 0);
delay(50);
}
void loop () {
myservo.write(90);
delay(15) ;
dist = analogRead(sensorpin);
Serial.print("Distance= ");
Serial.println(dist);
while (dist > 20) {
Forward();
dist = analogRead(sensorpin);
Serial.print("Distance= ");
Serial.println(dist);
Serial.println("Forward,distance>20");
}
while (dist <= 20) {
STOP();
myservo.write(pos);
delay(50);
dist = analogRead(sensorpin);
delay(1000);
Serial.print("POSTION: ");
Serial.println(pos);
select = pos;
pos += 45;
if (pos == 225) {
pos = 0;
}
}
myservo.write(90);
switch (select) {
case 0:
left();
delay(250);
STOP();
break;
case 45 :
left();
delay(500);
STOP();
break;
case 135 :
right();
delay(250);
STOP();
break;
case 180 :
right();
delay(500);
STOP();
break;
}
}