Pages: [1]   Go Down
Author Topic: While Loop  (Read 302 times)
0 Members and 1 Guest are viewing this topic.
Florida
Offline Offline
Newbie
*
Karma: 0
Posts: 48
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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?
Logged

Global Moderator
Offline Offline
Brattain Member
*****
Karma: 452
Posts: 18694
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Read this before posting a programming question


I'm surprised that compiled.

Copy and paste all your code please.

How to use this forum
Logged

Lost Wages
Offline Offline
Full Member
***
Karma: 11
Posts: 103
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

instead of

Code:
DigitalRead(Sensor) = sensorVal;

and then

Code:
While(sensorVal == HIGH)
{
   DigitalWrite(MotorPin, LOW);
   sensorVal = DigitalRead(Sensor);
}

DigitalWrite(MotorPin, HIGH);
Logged

Venezuela
Offline Offline
Jr. Member
**
Karma: 2
Posts: 74
The less You explain, the more I understand
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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,
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 13
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.


Logged

Offline Offline
God Member
*****
Karma: 10
Posts: 651
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Pages: [1]   Go Up
Jump to: