Hi,
Background
I’m building a simple, wheeled, obstacle avoiding Arduino robot. It consists of a wooden base with an Arduino Uno R3 and an Arduino sensor shield v.4.0 mounted on it. It’s powered by 4 AA batteries in a case. The servo motors are FS90R’s (plugged into 6 and 8 on the shield) and there is a Sharp GP2Y0A21YK0F Reflective (IR) distance Sensor mounted on the front.
Schematic
https://www.screencast.com/t/yvsozNTb
https://www.screencast.com/t/yvsozNTb
Code
#include <Servo.h>// Include servo library
Servo servoLeft; // Declare left servo
Servo servoRight; // Declare right servo
int IRpin = 0; // Analog pin for reading the IR sensor
float IRread; // Floating point number to hold converted voltage as distance
void setup() {
servoLeft.attach(6); // Attach left signal to P6
servoRight.attach(8); // Attach right signal to P8
}
void loop() {
getDistance();
if (IRread < 299) // NO OBSTACLE
{
forward();
}
else
{
dontGo();
}
}
void getDistance() {
IRread = analogRead(IRpin); // Reads the value of the sharp sensor
delay(50);
}
void forward() { // Create a forward subroutine
servoLeft.write(180);
servoRight.write(25);
}
void dontGo() {
servoLeft.write(90);
servoRight.write(90);
}
void leftTurn() {
servoLeft.write(90);
servoRight.write(0);
}
Problem
The motors work fine without the IR distance sensor but when I add the IR distance sensor code the motors start and stop at very short time intervals with a stuttering motion.
I’ve tried using millis() as an alternative to delay() but the motors still stutter. Removing the delay() completely makes the motors stutter at really short intervals.
Any help or ideas would be much appreciated, please. Many thanks!