Hello, I'm fairly new to arduino but university is trying to make me learn it. I'm currently building a robot that follow a light using 2 LDR sensor placed in 45degree on the front end of the robot to sense the light moving from left to right.
I have attached the code to this topic. The problem seems fairly simple but I cannot see it.
What I want to happen: right servo slow down then Right sensor is above the offset, meaning the light shines on the right side, and same thing for left side. The robot has only 2 wheel on stiff joint so it basically turn like a tank, a ball on the front end stabilize the robot.
What's currently happening: The servo starts smoothly and reach the maximum value of 180, but if i cover the light sensor with my hand or shine a flashlight on it, the servo will keep running at max speed.
I've been looking at my code for an hour or so and ran out of idea on how to fix this. So I'm turning to this forum!
any help or advice is appreciated! ![]()
#include <Servo.h>
Servo leftServo;
Servo rightServo;
int LLDR = analogRead(2);
int RLDR = analogRead(3);
int startSpeed = 180;
int lspeed = startSpeed;
int rspeed = startSpeed;
int rotate = 5;
int offset = 100;
void LRoffset()// adjust to the light movement left/right
{
if (LLDR > (RLDR + offset))
{
lspeed -= rotate;
leftServo.write(lspeed);
delay(100);
}
if (RLDR > (LLDR + offset))
{
rspeed -= rotate;
rightServo.write(rspeed);
delay(100);
}
lspeed = startSpeed;
rspeed = startSpeed;
leftServo.write(lspeed);
rightServo.write(rspeed);
}
void setup()
{
Serial.begin(9600);
leftServo.attach(9);
rightServo.attach(8);
pinMode(A2, INPUT);
pinMode(A3, INPUT);
for (int pos = 90; pos <= 180; pos += 2)
{
leftServo.write(pos);
rightServo.write(pos);
delay(100);
}
}
void loop()
{
LRoffset();
Serial.println(LLDR);
}
arduinoproject1.txt (950 Bytes)