I am currently controlling a servo with a potentiometer and trying to add some features for when it first turns on.
So I am trying to basically have the servo do the following:
Initialize the servo to zero degrees when I turn it on
Have the servo wait until the potentiometer position reaches zero the first time before moving
Once the potentiometer reaches zero the first time, the servo can now move from any potentiometer command
This way, the servo won't move to the initial potentiometer position when I first turn it on. It will wait until I zero the potentiometer before it moves anywhere else.
I am really struggling with the code for this. Any suggestions for how to approach this?
Sounds like a job for a small finite state machine. The below shows the framework that you can start with and expand.
void loop()
{
fsm();
}
void fsm()
{
enum STATES
{
HOME,
POTZERO,
RUN,
};
static STATES state = HOME;
switch (state)
{
case HOME:
Serial.println("Homing servo");
// set servo to 0 position here
Serial.println("Switching to POTZERO");
state = POTZERO;
break;
case POTZERO:
if (analogRead(A0) < 10)
{
Serial.println("Switching to RUN");
state = RUN;
}
break;
case RUN:
// do your potentiometer reading and moving of servo here
break;
}
}
There are three states.
In the first one (HOME), you move the servo to the 0 position; once that is done, you switch to the next state.
In the second one (POTZERO), you wait till the potentiometer reading is zero (I used 'less than ten' in case your potentiometer reading does not reach zero). If the condition is true, you switch to the next state.
In the last state (RUN) you can read the potentiometer and move the servo.
Alternative thought.
In setup(), move servo to initial position, pause for that to complete, then monitor pot for 0. When that happens, exit setup() and loop() takes over.