-
Help with loops..
If I want LED1 to blink 3 times and then LED2 3 times is there an "easier" way than this:
Code:
LED1 var PORTB.1
LED2 var PORTB.2
loop:
HIGH LED1
PAUSE 500
LOW LED1 'blink 1
PAUSE 500
HIGH LED1
PAUSE 500
LOW LED1 'blink 2
PAUSE 500
HIGH LED1
PAUSE 500
LOW LED1 'blink 3
PAUSE 500
HIGH LED2
PAUSE 500
LOW LED2 'blink 1
PAUSE 500
HIGH LED2
PAUSE 500
LOW LED2 'blink 2
PAUSE 500
HIGH LED2
PAUSE 500
LOW LED2 'blink 3
PAUSE 500
GOTO loop
END
Cant you only make something like this and get loop1 to repeat only 3 times and then start loop2.. ?
Code:
LED1 var PORTB.1
LED2 var PORTB.2
loop1:
HIGH LED1
PAUSE 500
LOW LED1
PAUSE 500
GOTO loop1
loop2
HIGH LED2
PAUSE 500
LOW LED2
PAUSE 500
GOTO loop2
END
So I want a loop that repeats itself 3 times and then starts loop2, how do I do that?
-
To execute a loop three times...
Example 1
Code:
CounterA var Byte
..
For CounterA=0 to 2
HIGH LED1
PAUSE 500
LOW LED1
PAUSE 500
Next CounterA
In the above example, counting starts at zero... it's the same as specifying
Code:
For CounterA=1 to 3
Example 2
Code:
CounterA var Byte
..
CounterA=3
While CounterA>0
CounterA=CounterA-1
HIGH LED1
PAUSE 500
LOW LED1
PAUSE 500
Wend
I'm sure a few more examples can be had too... but that's a starter...
-
Code:
X VAR BYTE
LED1 VAR PORTB.1
LED2 VAR PORTB.2
Main:
X = 0
REPEAT
HIGH LED1
PAUSE 500
LOW LED1
PAUSE 500
X = X + 1
UNTIL X = 3 ' pulse LED1 3 times
REPEAT
HIGH LED2
PAUSE 500
LOW LED2
PAUSE 500
X = X + 1
UNTIL X = 6 ' pulse LED2 3 times
GOTO Main
END
-
Not to make this a contest of "How many ways can you...", but I thought another example, using different logic, would also be instructive.
Code:
X VAR BYTE
LED1 VAR PORTB.1
LED2 VAR PORTB.2
X = 0 ' Reset Iteration Count
Loop:
IF X < 3 THEN ' Iterations 0,1,2
HIGH LED1
PAUSE 500
LOW LED1
PAUSE 500
ELSE ' Iterations 3,4,5
HIGH LED2
PAUSE 500
LOW LED2
PAUSE 500
ENDIF
X = X + 1 ' Increment Iteration Count
IF X < 6 THEN Loop ' Loop back if less than 6 iterations
END
So, now you have examples using all of the following:
FOR...NEXT
WHILE...WEND
REPEAT...UNTIL
IF...THEN
All of these will produce the same results, just with subtle differences in the logic used to accomplish the task, making this tread a nice little study.
HTH,
SteveB