Robotics & Arduino
Lesson 2 · Refinement

GPT SOLUTION

Your plan, written as logic, pseudocode, and Arduino code.

01 — Think it through.

Initialize: start at 0°, make one full sweep, and remember the brightest reading and its angle. Go back to that angle.

Watch: stay there while the light is good enough. If the reading drops by more than our buffer, search nearby.

Search: randomly choose a direction and move a few degrees at a time. If the light increases, keep going.

Reverse: if it dims before improving, return to the starting position and try the other direction. If it improves and then dims, return to the best angle we found and stay there.

Reset: if the next step would leave the allowed range without finding good enough light, do a full sweep. Also rescan if the light is lost or neither direction helps.

BUFFER = 100 · GOOD = 900 · LOST = 100

Compare fading against the remembered reading, not just the previous sample. That way, several small drops can add up to a search.

These thresholds are starting guesses. Check room light and phone-flashlight readings in Serial, then adjust them. “Lost” must suit the room’s background light; it may never fall below 100. Use the servo limits you already tested.

02 — Write pseudocode.

03 — Add the Arduino code.

INCLUDE → DECLARE → INIT → RUN → LOGIC.

loop() says what happens. The functions handle one job each: decide, scan, search nearby, move, or read.

Download the Arduino sketch

Assumes the LDR is toward 5V and the fixed divider resistor is toward GND: brighter means a higher A0 reading. Servo signal is D9; use the servo power arrangement already tested, with a common GND. Open Serial Monitor at 9600 baud.

Read the flags: movingForward chooses the direction. ! flips true to false or false to true. foundImprovement remembers whether this search got brighter. switchedDirection prevents repeatedly trying the same two directions.

Test it slowly: scans and searches finish before loop() continues. Move the phone slowly and watch the readings. A scan takes time; this beginner version uses delays so the movement can settle before each reading.

A short opaque tube around the LDR helps make the reading depend on direction. Serial’s angle is the command we sent, not position feedback from the servo.