Using Switch Statement in C Programming for Microcontrollers

The C language also provides another way for multi-branch selection using the switch statement, which has the general form:switch(expression){ case constant_expression1: statement1; case constant_expression2: statement2; case constant_expressionn: statementn; default: statementn+1;}The semantics are: calculate the value of the expression. Then compare it one by one with the subsequent constant expression values. When the value of the expression is equal to the value of a certain constant expression, execute the subsequent statement, and no further judgments are made; continue executing all statements after the following cases. If the value of the expression does not match any of the constant expressions after all cases, execute the statement after default.

The program to control the lighting state of an 8-bit LED on port P0 using the switch statement is as follows:

#include<reg51.h> // Include the header file for microcontroller registers

sbit K5=P1^4; // Define K5 as P1.4

/*****************************

Function: Delay for a period of time

*****************************/

void delay(void)

{

unsigned int n;

for(n=0;n<20000;n++)

;

}

/*****************************

Function: Main function

*****************************/

void main(void)

{

unsigned char i;

i=0; // Initialize i to 0

while(1)

{

if(K5==0) // If the S1 button is pressed

{

delay(); // Delay for a period of time to debounce the button

if(K5==0) // If S1 button is detected pressed again

i++; // Increment i by 1

if(i==9) // If i=9, reset it to 1

i=1;

}

switch(i) // Use multi-branch selection statement

{

case 1: P0=0xfe; // First LED on

break;

case 2: P0=0xfd; // Second LED on

break;

case 3:P0=0xfb; // Third LED on

break;

case 4:P0=0xf7; // Fourth LED on

break;

case 5:P0=0xef; // Fifth LED on

break;

case 6:P0=0xdf; // Sixth LED on

break;

case 7:P0=0xbf; // Seventh LED on

break;

case 8:P0=0x7f; // Eighth LED on

break;

default: // Default case, turn off all LEDs

P0=0xff;

}

}

}

When using the switch statement, the following points should also be noted:

  1. The values of the constant expressions after case cannot be the same; otherwise, an error will occur.

  2. Multiple statements are allowed after case and do not need to be enclosed in {}.

  3. The order of each case and default clause can be changed without affecting the program execution result.

  4. The default clause can be omitted.

Leave a Comment