Solar Tracker Limit Switches

Hey Guys,

im programming my solar tracker. it is a one axis tracker and has two limit switches. In the evening when it hits the western limit switch it shall turn to the other direction until it hits the eastern limit switch.

Im programming with a if and while loop it looks like that.

if(LimitswitchWest == HIGH)
{
Serial.println(“Western limitswitch got hit”);

while(LimitswitchEast == LOW && LimitswitchWest == HIGH)
{
for(int i=0; i<Steps; i++)
{
digitalWrite(DIR,HIGH);
digitalWrite(ENA,LOW);
digitalWrite(PUL,HIGH);
delayMicroseconds(Timea);
digitalWrite(PUL,LOW);
delayMicroseconds(Timea);
}
Serial.println(WertEndschalterWest);
}
}

I already know that this can not work because as soon as the western switich is not pushed anymore the if condition is not true anymore.

Im looking for something like --When switch was hit, do that until other switch is hit. Dont know the code for that.

No while loops.

Think state machine. Your code is in one of two states.

  1. Moving to the west tracking the sun
  2. Moving back to the east.

Pseudocode.

int state = 0;

void loop(){

   if (state == 0){
        // track the sun one step to the west
        if(limit switch is hit){
              state = 1;
        }
   }
   else if (state == 1){
        // move to the east by one step
        if(east limit switch is made){
             state = 0;
        }
   }
}

Another option:

enum {WEST, EAST} state;
switch (state)
{
	case WEST:
		// do west stuff
		break;
	case EAST:
		// do east stuff
		break;
}

Instead of trying to do everything in loop(), suppose you wrote some functions.

void loop()
{
   // some code here to read the west limit switch
   if(LimitswitchWest == HIGH)
   {
      moveToEastLimit();
   }
}

Now, what would the moveToEastLimit() function look like?

I already know that this can not work because as soon as the western switich is not pushed anymore the if condition is not true anymore.

Nonsense. There is NOTHING in the code you posted that checks LimitswitchEast or LimitswitchWest, so the values in those variables do not change when the while statement is running, so the while loop will never end. But, that is NOT the problem that you identified.

Read the west limit switch. If it is pressed, move until you read that the east limit switch is pressed.