Go Down

Topic: Help with a while loop (Read 322 times) previous topic - next topic

be80be

This sure is not basic could any one show the right way to write this
Code: [Select]
void loop(){
   int x = 0;
 while(RX == HIGH; && x < 8;){
     delay(1000);
     x = ++x;
 }

el_supremo

Get rid of the semicolons in the while condition and just to be safe parenthesize the conditions:
Code: [Select]
  while((RX == HIGH) && (x > 8)) {

Pete

guix

If it was my code I would write it like this:
Code: [Select]
void loop()
{
  uint8_t x = 0;
  while( RX == HIGH && x < 8 )
  {
    delay( 1000 );
   x++;
 }
}

PeterH

If it was my code I'd write it like this:

Code: [Select]

void loop()
{
    unsigned long start = millis();
    while((millis() - start < 8000UL) && (RX == HIGH))
    {
    }
    // when we get here RX is low or 8000ms has elapsed
}


The advantage over the original code is that changes to RX are detected as soon as possible rather then only once per second. I assume you are using an interrupt to update RX.
I only provide help via the forum - please do not contact me for private consultancy.

be80be

#4
Nov 18, 2012, 10:57 pm Last Edit: Nov 18, 2012, 11:08 pm by be80be Reason: 1
I done the same code in swordfish basic  but can't get the loops right

This is what I'm trying to do I have a 315Mhz RF link kit The transmitter is on a pic 10F200 with three button switches .

You press  sw1 and it sends a 8mS high then a low of 8mS then 8 1mS pulses.

I want to get the start pulses
I tried some thing like this
Code: [Select]
int RX = 3;
void setup(){
  Serial.begin(9600);
  pinMode(RX, INPUT);
}

void loop(){
   Serial.println("Here we go again");
     unsigned long start = millis();
         while((millis() - start < 8000UL) && (RX == HIGH)){
   Serial.println("Here we where not");
    delay(100);
         }
}

Delta_G

Code: [Select]
int RX = 3;
void setup(){
...
  pinMode(RX, INPUT);
}

void loop(){
   ...
         while((millis() - start < 8000UL) && (RX == HIGH)){
 
         }
}


I think HIGH is defined to be 1, so it will never equal 3 and your while loop will never loop.  The expression will be false every time. 

Maybe you meant to do a digitalRead on that pin instead of comparing the pin number to HIGH.

Something like

Code: [Select]
while((millis() - start < 8000UL) && (digitalRead(RX) == HIGH))


be80be

#6
Nov 18, 2012, 11:35 pm Last Edit: Nov 18, 2012, 11:44 pm by be80be Reason: 1
Delta_G I think that's it I was thinking RX == HIGH is the same as digitalRead(RX) == HIGH
Yep that picked up the start bit of 8mS now I see

Arduino code may be easy if you never coded in Basic I figured where i set pinmode of RX would let me just read RX wrong LOL My code I started with works to after fixing that one thing.

PaulS

Quote
Arduino code may be easy if you never coded in Basic

Any programming language is easier to learn when you don't have to first unlearn all the bad habits you picked up starting with Basic.

Go Up