Switch statement not working

mikroC, mikroBasic and mikroPascal PRO for Microchip’s 8-bit PIC MCUs.
Post Reply
Author
Message
Sobrietytest
Posts: 619
Joined: 05 Jul 2008 06:05
Location: Thailand

Switch statement not working

#1 Post by Sobrietytest » 14 Jun 2021 08:11

I have a PIC Clicker set up driving a stepper motor, it is set up for USB and it decodes the incoming commands from a PC. One of the incoming commands invokes a motor test whereby the speed and direction of the motor can be set on the PC.

The decoder reads the first byte ('$') to check whether the message is valid. it then reads the second and third bytes as a directive (M, T, in this case) to invoke the motor test. The fourth byte is the motor speed in rev/sec (range of 1 - 9). The fifth byte is ignored and the sixth byte sets the motor direction.

Here's the code...

Code: Select all

else if((readbuff[1] == 'M')&&(readbuff[2] == 'T')){ //Motor test
      //WRITE CODE test motors

          //spd = readbuff[3];
          switch (readbuff[3]){             // Speed select
            case '1': DelayCnt = 500;
            case '2': DelayCnt = 250;
            case '3': DelayCnt = 167;
            case '4': DelayCnt = 125;
            case '5': DelayCnt = 100;
            case '6': DelayCnt = 83;
            case '8': DelayCnt = 63;
            case '9': DelayCnt = 56;
            default: DelayCnt = 500;
            }

            if(readbuff[5] == '1'){         // Motor direction
               MD1 = 1;
               }
            else{
                MD1 = 0;
                }
          for(gg = 0; gg < 5; gg++){        // Spin 5 turns
              Turn();
          }

      }
At the moment, the Clicker reads the command and spins the motor in the selected direction, but the speed is always the default value.

I am monitoring the output array from the PC in a watch window and all the elements are correct. I have tried using hex and decimal comparison (i.e case 0x31: DelayCnt = 500; or case 49: DelayCnt = 500;) but the result is the same.

Any ideas why the Switch statement isn't working?

Sobrietytest
Posts: 619
Joined: 05 Jul 2008 06:05
Location: Thailand

Re: Switch statement not working <SOLVED>

#2 Post by Sobrietytest » 14 Jun 2021 09:20

As the switch can only concur with one case, I didn't think the break; was necessary. Turns out it is!

Code: Select all

switch (readbuff[3]){             // Speed select
            case '1': DelayCnt = 500; break;
            case '2': DelayCnt = 250; break;
            case '3': DelayCnt = 167; break;
            case '4': DelayCnt = 125; break;
            case '5': DelayCnt = 100; break;
            case '6': DelayCnt = 83;  break;
            case '8': DelayCnt = 63;  break;
            case '9': DelayCnt = 56;  break;
            default: DelayCnt = 500;  break;
            }
Anyhoo, problem solved.

Post Reply

Return to “PIC PRO Compilers”