Photocell as switch to step a program?

I am trying to write a program where a servo will have 5 positions and a photocell will be used as the input to detect (from dark to light) and make the servo step to the next position. when the last position is reached it will restart the sequence.

(dark to light) servo position 1
(dark to light) servo position 2
(dark to light) servo position 3
(dark to light) servo position 4
(dark to light) servo position 5
(dark to light) servo position 1

Photocell has a pull down resistor and input to pin A0
Servo signal is PWM Digital pin 2

I can take a picture later but that's all I have wired. not much to it. I'm not sure how to start this project honestly.

Show us a good schematic of your circuit. Show us a good image of your ‘actual’ wiring.
Give links to components.


In the Arduino IDE, use Ctrl T or CMD T to format your code then copy the complete sketch.
Use the </> icon from the ‘reply menu’ to attach the copied sketch.

Start with the servo sweep example. When you get the example to work. Then learn how to read the Analog to digital converter to read the photocell. Then combine the code. Make postings on your progress and ask for help when you get stuck.

Just work with one servo and one photocell to work then it will be, mostly, a matter of duplication.

Definitely you'd benefit from learning about state machines and state transition diagrams - this is the way to design and think about your code.

A problem you are likely to encounter with a photocell (whether LDR or photodiode/transistor) is
noise and multiple transitions - the solution to this is using some hysteresis in
detecting light/dark transistions, or perhaps some debounce logic.

Or better yet, use photodiodes instead of slow LDR's.

Hi, @BadWolfEmpire
Welcome to the forum.

Please read the post at the start of any forum , entitled "How to use this Forum".

Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

Thanks.. Tom.. :grinning: :+1: :coffee: :australia:

I would think LDRs are pretty fast compared to servos.

Please understand that "photocell" isn't a very good technical term. It can mean one of several different types of component, that need to be used in different ways. For example Light-Dependant Resistors (LDRs), Photodiodes and Phototransistors. It sounds like you are using an LDR but a picture or link would help us identify it for you.

As with all problems, you break them down and solve one part at a time. The example sketches that come with the IDE are a good place to find a little code to solve one part of the problem. For one example, try the "AnalogReadSerial" for reading your LDR, another would be the StateChangeDetection for counting the number of dark-to-light changes, and the Sweep example that comes with the Servo library.