Go Down

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

schoolsterz123

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
http://www.gammon.com.au/electronics

MaJiG

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);

alah

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

If (  digitalRead ( sensorval) == HIGH )
{
digitalWrite ( motorpin , LOW );
}
Else
{
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,

daveclark5

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.



Delta_G

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.

Go Up