However the Arduino code link provided (lollipop01) does not work as it should at all. Firstly the ultrasonic sensor is not detecting any obstacles but moving forward and reverse in random order hitting obstacles along the way. Secondly the Gear Motor does not function properly but stops randomly for a prolonged period of time without any scope. Do you think you could please help me solve these problems? I need an obstacle avoidance robot that DETECTS an OBSTACLE and AVOIDS it! This is highly important as it for University assignment purposes.
Code:
// Magic03
// This code is designed for the Lollipo DIY Chassis
// Uses an HC-SR04 Ultrasonic Sensor on the front steered axle
//
// The motors are controlled using the Adafruit Motor shield library
// which must be downloaded and installed first
// copyright Adafruit Industries LLC, 2009
// this code is public domain, enjoy!
#include <AFMotor.h>
#include <Servo.h>
AF_DCMotor motor(4);
int steerPin = 10; // this is Servo 1 on the motor shield
Servo steerServo;
int pingPin = A0; // Analog pin 0 used for the Ping Pin (Trig)
int inPin = A1; // Analog pin 1 used for the Echo Pin (Echo)
unsigned long duration, inches;
int indec, cmdec;
int inchconv = 147; // ratio between puls width and inches
int cmconv = 59; // ratio between pulse width and cm
String s1, s2, s3;
int steerCentre = 80; // set this to be dead ahead setting (or adjust servo horn mounting)
void setup()
{
//Serial.begin(115200);
pinMode(pingPin, OUTPUT);
pinMode(inPin, INPUT);
steerServo.attach(steerPin, 1000, 2000);
steer(0);
}
void loop()
{
int cm, lcm, rcm;
forward(200);
delay(200);
cm = getDistance();
if(cm < 20)
{
halt();
steer(-60);
lcm = getDistance();
steer(60);
rcm = getDistance();
steer(0);
if (lcm < rcm)
steer(-45);
else
steer(45);
reverse(180);
delay(700);
steer(0);
}
}
void steer(int angle)
{
steerServo.write(steerCentre + angle);
delay(800); // wait for servo to get there
}
int getDistance()
{
int rval;
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
duration = pulseIn(inPin, HIGH, 38000L); // Set timeout to 38mS
if (duration == 0)
duration = 1000;
rval = microsecondsToCentimeters(duration);
// Serial.println(rval);
return rval;
}
void forward (int spd)
{
motor.run(FORWARD);
motor.setSpeed(spd);
}
void reverse(int spd)
{
motor.run(BACKWARD);
motor.setSpeed(spd);
}
void spinLeft(int spd)
{
}
void spinRight(int spd)
{
}
void halt()
{
motor.run(RELEASE);
delay(10);
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / cmconv;
}
Thank you
Lollipop01.ino (2.14 KB)