While loops

I tried today to use while loops in my program. The code was compiled noramlly, but after I downloaded the program the program state LED was blinking and the controller seemed to be stuck. the problem is the while loop for sure.

I know that a while loop is included in the main function, but can it be used somewhere else?




Im programming using MPLAB

I don’t know if this applies to the vex controller too, but the RC gives an error if the code loop takes too long to finish, this may be your problem.

This really depends on what the while loop does. If it’s say, something to the effect of:

int i = 0;
while(i < 10) {

then certainly you can do it. If, instead you’re doing something relying on external sensors/states. For example, in pseudo code:

while(button is pushed) {
  do stuff

then you won’t get anywhere because whether or not the button is pushed isn’t going to be updated within your function (that updating in some of the FIRST-provided code which you don’t need to and shouldn’t modify; but, if you’re curious you can look). If your code doesn’t let the program flow continue to the FIRST-code which updates buttons you just won’t have the new status of the button being pushed (and as a result you’ll be stuck).

It’s probably worth noting that your user code is already in a big while loop (the one you rightly pointed out is in the main function) and as a result already will be called repetitively.

Something else to note:

The RC does some processing each loop that lets it know that it’s still alive. If it doesn’t get to that processing in a timely manner (i.e. if you’re in a tight loop), the master processor in the RC generate a code error. If you’re not familiar with this process, it’s referred to as a watchdog timeout.

I would suggest reevaluating why you’re using a while loop in your RC code. If you’re looping over a small amount of data (like a lookup table) you should be fine, but if you’re doing serious data processing in the loop you may want to find an alternate way to perform the same task. As Timothy mentioned, there’s already a loop within the RC code. Can you leverage that?

How come that while loops are a possible option in EasyC but not in MPLAB?
The while loops I had was quiet basic. I wanted to do some heavy calculation in the while loop, but I guess I’ll have to change it with SWITCH and IF statements.

It all depends on the complexity of the program. If you’re not doing much, while loops can work. It’s when you start hogging the processesor that you run into problems. My guess is that you had a relatively small program with your EasyC, but somthing that’s a little more complex now.

Easy C uses a timer interrupt to do getData and putData.

In MPLAB getData and putData are called from the “main” while loop. If you code an inner while loop which does not call getData and putData, the error light will flash.