stuck in a 'while' loop

Hi here goes,

I am working with a modified servo as I need it to continuously rotate, therfore it’s own pot is disabled. For this reason I have coupled it to a rotary encoder so that I can tell where it is, and this is all working very nicely. Eventually, I am planning to have several IR sensors that when triggered will make the motor continue (it is already rotating) to a certain position and stop until motion ceases whereupon continual rotation will be reinstated. Right now I’ve just got one sensor hooked up, the motor rotating and I’m managing to stop the servo at a certain encoder reading using a ‘while’ statement. Only problem is, it then gets stuck in the loop and the sensor pin stays HIGH. I’ve been trying to insert a break but haven’t had much luck, I’ve also tried using ‘do’ in conjunction with ‘while’ again without much luck, I also tried putting a delay in but then the servo seemed to stop whatever the encoder reading was. Can anyone help me out?

if (val == HIGH){ //sensor triggered
while (encoderPos == 6) //if encoder reads 6…
pulseWidth = stopServo; //stop

if (val == LOW){ //sensor inactive
pulseWidth = turnServo; //turn servo

You may know this already but if not then I hope this helps:

if encoderPos is updated from an interrupt, it must be declared volatile, otherwise the compiler will optimize it out of that code. If it is not updated in an interrupt then you need to update it in that code.

If your servo library is not pulsing the servo in an interrupt then you need to refresh the servo every 20ms.

Thanks for the reply, I am quite new to this so I may have made a simple error.

encoderPos is declared volatile and then updated in an interrupt called doEncoder:

attachInterrupt(0, doEncoder, CHANGE); // encoder pin on interrupt 0 - pin 2

I've been watching it in serial and it all seems fine.

The servo is being refreshed every 20ms, if I take the 'while' statement out of the code I can stop the servo with sensorPin HIGH and then it starts again when the sensor pin goes back to low. So the servo side should be fine??

If you change:

while (encoderPos == 6) //if encoder reads 6…
pulseWidth = stopServo; //stop


while (encoderPos == 6) //<— also, make sure there is no semicolon here

Do you stop seeing the dots when the encoder positions changes?

OK, when it gets to 6 and the sensorPin is high, the dots start printing and it gets stuck in the loop. If I then manually change the encoder the dots stop, the servo carries on and the sensor behaves normally again.

If you want to exit the while loop when the sensor value changes even if the decoder position is still equal to 6, you could do something like:

while ( (encoderPos == 6) && (digitalRead(sensorPin) == HIGH) ) // loop until either changes

Ahh, that’s got it! Thankyou very much for your help, much appreciated.