Go Down

Topic: While Loop (Read 729 times) previous topic - next topic


In my code I have something such as:

DigitalRead(Sensor) = sensorVal;

While(sensorVal == HIGH){
  DigitalWrite(MotorPin, LOW);}
DigitalWrite(MotorPin, HIGH);

However, the while loop never terminates regardless of what the sensorVal is. What am I doing wrong here?

Nick Gammon

Read this before posting a programming question

I'm surprised that compiled.

Copy and paste all your code please.

How to use this forum
Please post technical questions on the forum, not by personal message. Thanks!

More info:


Do you mean
Code: [Select]
sensorVal = DigitalRead(Sensor);

instead of

Code: [Select]
DigitalRead(Sensor) = sensorVal;

and then

Code: [Select]

While(sensorVal == HIGH)
  DigitalWrite(MotorPin, LOW);
  sensorVal = DigitalRead(Sensor);

DigitalWrite(MotorPin, HIGH);


It  seem s you  want  to control something. Why not try

If (  digitalRead ( sensorval) == HIGH )
digitalWrite ( motorpin , LOW );
digitalWrite  ( motorpin, HIGH );

Never the less, NIck Gammon is expert; post your code.
BTW, take some advice as I was given: go to TOOLS and select AUTOFORMAT, place your parenthesis at the beginning of the next line,


What editor allows an upper case "Else"?

Another thing that happens sometimes (but not here) is that the "="  (which assigns a value) is used instead of "==" (which tests for a condition).  But you got that.

As a total aside - here is a cute while loop little exercise i just bumped into.

   while(button(BUTTON1) || button(BUTTON2) || button(BUTTON3));

button is a user defined function and BUTTON1 is an integer.  This while loop cycle through each time and continues to cycle by testing the or (||) until button() returns 0 for all three.


Somewhere in that loop you need to update sensorVal.  If you don't do another digital read in there then sensorVal will never change and always be HIGH and the loop will never end.
Ad hoc, ad loc, and quid pro quo.  So little time - so much to know!  ~Jeremy Hillary Boob Ph.D

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131