Maker Pro
Maker Pro

How to use switch statement

vead

Nov 27, 2011
473
Joined
Nov 27, 2011
Messages
473
How to use switch statement in C program. I want to use switch statement in program. I am using keil compiler I tried to use switch statement in program. whats wrong in program and how to correct ?
blink three LED's for different times
Code:
#include<reg51.h>    //header file
 
#define  LED1_ON   1
#define  LED1_OFF  0
#define  LED2_ON   1
#define  LED2_OFF  0
#define  LED3_ON   1
#define  LED4_OFF  0
 
sbit   LED1     = P2^0;    //LED 1 conncted to port P2 pin 0
sbit   LED2     = P2^1;    //LED 2 conncted to port P2 pin 1
sbit   LED3     = P2^2;    //LED 3 conncted to port P2 pin 2
 
typedef enum
{
    task1,
    task2,
    task3
};
// prototype function
void LED1_Blink(void);
void LED2_Blink(void);
void LED3_Blink(void);
int main(void)
{
   unsigned int task=0;
 
    while(1)
  {
   switch  (task)
   {
      case task1:
                 if (task == task1)
                 {
                    LED1 = LED1_ON;
                    LED1_Blink();
                    LED1 = LED1_OFF;
                 }
         break;
 
      case task2:
                 if (task == task2)
                 {
                      LED2 = LED2_ON;
                      LED2_Blink();
                      LED2 = LED2_OFF;
                 }
         break;
 
      case task3:
                 if (task == task3)
                 {
                    LED3 = LED3_ON;
                    LED3_Blink();
                    LED3 = LED4_OFF;
                 }
         break;
   }
}
}
 
void LED1_Blink ()
{
    unsigned int i;
    for (i = 0; i < 1000; i++);
}
 
void LED2_Blink()
{
    unsigned int j;
    for (j = 0; j < 1500; j++);
}
 
void LED3_Blink()
{
   unsigned int k;
    for (k = 0; k < 1200; k++);
}
Code:
function.c - 0 Error(s), 0 Warning(s).
 

(*steve*)

¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd
Moderator
Jan 21, 2010
25,510
Joined
Jan 21, 2010
Messages
25,510
Google

OK, I'm opening it again. You need to do some work for yourself.

Please start by explaining how you think your code should work.
 
Last edited:

vead

Nov 27, 2011
473
Joined
Nov 27, 2011
Messages
473
Google

OK, I'm opening it again. You need to do some work for yourself.

Please start by explaining how you think your code should work.
I understood My mistake I haven't shown my effort to solve the problem but believe me I tried my best level to understand switch statement. First I studied what is switch statement in c programming and than I wanted to use that switch statement in program because I love to work with microcontroller and LEDs. so that's why I wrote program for LED. I understand use of switch statement but when I tried to test with LED's I could not get success

I have written code for LED Blinking. I know first I have to write header file. If I don't include header file. compiler will give error than, I have to define port or I have to set port pins.because I have to tell to compiler how are LEDs are connected to microcontroller. so I have written following define and sbit statment for three LED's
Code:
#include<reg51.h>    //header file
 
#define  LED1_ON   1     // turn on LED1
#define  LED1_OFF  0    //Turn off LED1
#define  LED2_ON   1     //turn on LED2
#define  LED2_OFF  0     // turn off LED2
#define  LED3_ON   1      // turn on LED 3
#define  LED4_OFF  0    // turn off LED 3
 
sbit   LED1     = P2^0;    //LED 1 conncted to port P2 pin 0
sbit   LED2     = P2^1;    //LED 2 conncted to port P2 pin 1
sbit   LED3     = P2^2;    //LED 3 conncted to port P2 pin 2

Enum statement: I am explaining why I use enum statement because I have to do three task. I want to do one by one. here enum statment define three task and first task assign value with 0 than next will be increment by 1. like following
task1=0
task2 =1
task3= 2

Code:
typedef enum
{
    task1,       
    task2,
    task3
};

than declared prototype functions
Code:
// prototype function
void LED1_Blink(void);
void LED2_Blink(void);
void LED3_Blink(void);

than I was referring below side for switch case statement
https://www.tutorialspoint.com/cprogramming/switch_statement_in_c.htm
http://www.studytonight.com/c/switch-statement-in-c.php
I declared variable task and assign with 0 value
Code:
int main(void)
{
   unsigned int task=0;
 
    while(1)
  {
   switch  (task)
   {
      case task1:
                 if (task == task1)
                 {
                    LED1 = LED1_ON;
                    LED1_Blink();
                    LED1 = LED1_OFF;
                 }
         break;
 
      case task2:
                 if (task == task2)
                 {
                      LED2 = LED2_ON;
                      LED2_Blink();
                      LED2 = LED2_OFF;
                 }
         break;
 
      case task3:
                 if (task == task3)
                 {
                    LED3 = LED3_ON;
                    LED3_Blink();
                    LED3 = LED4_OFF;
                 }
         break;
   }
}
}

I have doubt because I think I need use for loop so that it will be run on three time for (task=0; task>2; task++);

after that I created three different delays because I want to different time for three leds
Code:
void LED1_Blink ()
{
    unsigned int i;
    for (i = 0; i < 1000; i++);
}
 
void LED2_Blink()
{
    unsigned int j;
    for (j = 0; j < 1500; j++);
}
 
void LED3_Blink()
{
   unsigned int k;
    for (k = 0; k < 1200; k++);
}

I just want to ask someone what's wrong with program. I am applying concept that I know already. my code is not working on hardware means there is problem in my program. I am asking what's wrong in program?
 

Irv

Jun 7, 2017
112
Joined
Jun 7, 2017
Messages
112
Many things wrong.

First, explain why you need LED1_ON, LED2_ON, etc. when they all evaluate to the same value, 1,
while all LEDx_OFF evaluate to 0?

Secondly, why are you changing the port assignments of LED1, LED2, and LED3 from their original values to 0 or 1?

Third, please explain why 3 different functions are needed to in order to blink for 3 different time periods?

Forth, try to explain in plain english what you expect your program to do. If you can't do that, you'll never be able to write a C program to do it (with, or without help).
 

JWHassler

Dec 22, 2014
86
Joined
Dec 22, 2014
Messages
86
You have not said what you mean by "does not work."
That said, make sure that the LEDs work by blinking them several (or several hundred) times just after reset
Until you know that your hardware works, you can't say that the program is faulty
 

Irv

Jun 7, 2017
112
Joined
Jun 7, 2017
Messages
112
Under normal conditions, testing hardware is a good idea. However, in this case, a glance at the code tells me that would be fruitless - that code can't work. So yeah, you *can* say the program is faulty.
How faulty depends on what he actually wants it to do, if he can't explain that, nobody can help with the code.

I'm guessing this is a class assignment. If so, either he has been sleeping in class, or has a very poor teacher. Look at the *_Blink() functions. See anything wrong there? Does the fact that there are 3 tell you anything about how much he has been taught?

So, again, first step: Write down exactly what this is supposed to do.
 

(*steve*)

¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd
Moderator
Jan 21, 2010
25,510
Joined
Jan 21, 2010
Messages
25,510
I doubt it's a class assignment. He's been going on at trying to program this thing for ages without bothering to learn the language he's using.

If I recall correctly, vead began long ago with the question "is windows or Unix a better real time operating system" and has progressed to finding neither run on a microcontroller. His aim in life now seems to be to write an RTOS for microcontrollers. However he has never thought it necessary to learn to program in C/C++ and not does he see that as an impediment.

This thread actually marks a major step forward for vead. Notwithstanding that the question he asks can be answered by typing it directly into Google, he has actually asked a question which can be answered.

The fact that his code will never do what is intended with the given structure is a side issue.

If vead can explain what he thinks the body of the code is doing, then we can (at least) fix his understanding of how the carrots statements work.
 

Harald Kapp

Moderator
Moderator
Nov 17, 2011
13,700
Joined
Nov 17, 2011
Messages
13,700
Code:
{
      case task1:
                 if (task == task1)
                 {
                    LED1 = LED1_ON;
                    LED1_Blink();
                    LED1 = LED1_OFF;
                 }
         break;
Here you have at least some redundancy which is not required:
Code:
   switch  (task).
The statements after "case Task1:" will be exexuted only if task ==1, therefore the if clause is unnecessary.

[CODE]      case task3:
                 if (task == task3)
                 {
                    LED3 = LED3_ON;
                    LED3_Blink();
                    LED3 = LED4_OFF;
                 }
         break;
Why LED4_OFF when two lines above LED3_On was set?

Code:
void LED1_Blink ()
{
    unsigned int i;
    for (i = 0; i < 1000; i++);
}
 
void LED2_Blink()
{
    unsigned int j;
    for (j = 0; j < 1500; j++);
}
 
void LED3_Blink()
{
   unsigned int k;
    for (k = 0; k < 1200; k++);
}
2 comments here:
  1. These loops will be incedibly fast, if not deleted completely from the code by the optimization routine of the compiler. You will need much higher values for the loop counter to create a noticeable effect. I recommend you use a delay fnction from a library. Usually such a function is part of a development system. Look up delay() or similar in your documentation, help files or header files.
  2. It is not meaningful to pump up the code with three subroutines where one subroutine can suffice which takes the tiem for delay as a parameter (see delay()).
Code:
   unsigned int task=0;
This seems to be the main issue: you set task=0, but there is no place in the code where task gets assigned another value from the enum list. Therefore the switch statement will never evaluate to one of the three states (task1, task2, task3). A default statement for the switch is aso missing, therefore the whole loop will do nothing at all.
It is also not good programming practise to mix direct assignments of values and picking values from e.g. an enum table. In this case it would be much more clear if the enum table contained a 4st state, e.g. task_initial and you'd use this instead of task = 0;
Code:
typedef enum
{
    task_initial,
    task1,
    task2,
    task3
};
// prototype function
void LED1_Blink(void);
void LED2_Blink(void);
void LED3_Blink(void);
int main(void)
{
   unsigned int task=task_initial;
 
    while(1)
plus some place in the code where an assignment of task to task1, task2 or task3 happens.

You may also want to learn about the volatile keyword to avoid compiler optimizations that lead to unexpected compiler results (deleted code, deleted variables etc. due to optimization).
 

vead

Nov 27, 2011
473
Joined
Nov 27, 2011
Messages
473
I'm guessing this is a class assignment. If so, either he has been sleeping in class, or has a very poor teacher
No this is not school assignment. I am trying to learn myself by using internet. if you will see my old thread's I have been written c program for LED blinking , LCD display and Motor based project's. that was easy projects after that I decided to add complex project than I wanted to do all in one project. means I was trying to write program where first task was led binking and second task was motor on/off and third task Display message.

I created thread https://www.electronicspoint.com/threads/need-help-in-program.284238/ but there I didn't get much response. so than I decided first I will do experiment with LED's. blink first led than second led than third led because I already written c program for LED. so that's the reason I was trying to write this program.

If I recall correctly, vead began long ago with the question "is windows or Unix a better real time operating system" and has progressed to finding neither run on a microcontroller. His aim in life now seems to be to write an RTOS for microcontrollers. However he has never thought it necessary to learn to program in C/C++ and not does he see that as an impediment
Yes I have been asked some questions on real time operating system. and Yes I want to write small RTOS program for microcontroller just for learning purpose . but now I am focused only on c programming. again you will see my old thread you will see that i was learning basic about c programming

This thread actually marks a major step forward for vead. Notwithstanding that the question he asks can be answered by typing it directly into Google, he has actually asked a question which can be answered
I feel that I don't deliver what I want to ask because english is not my first language. I think that people thinks about me that I am rude. I don't follow their advice. but believe me always respect all members and I always try to give my best.

The fact that his code will never do what is intended with the given structure is a side issue.

If vead can explain what he thinks the body of the code is doing, then we can (at least) fix his understanding of how the carrots statements work.
I just wanted to learn how to write program for multitask. first blink LED, than Run Motor than display message. that was complex task so I tried to write program blink LED1 than Blink LED2 than Blink LED3

Harald kapp
thank you very much for your time and explanations

If so, either he has been sleeping in class, or has a very poor teacher.
I was not sleeping. I was just trying to understand where I am doing mistake. than I went step by step first I tried to understand enum with example than switch case statement than tried to apply all concept in my program and at end my program run successfully on microcontroler.

Here is my working code. I have tested it works fine
Code:
#include<reg51.h>    //header file
 
#define  LED1_ON   1
#define  LED1_OFF  0
#define  LED2_ON   1
#define  LED2_OFF  0
#define  LED3_ON   1
#define  LED3_OFF  0
 
sbit   LED1     = P2^0;    //LED 1 conncted to port P2 pin 0
sbit   LED2     = P2^1;    //LED 2 conncted to port P2 pin 1
sbit   LED3     = P2^2;    //LED 3 conncted to port P2 pin 2

enum mytask {
  task1 = 1,
  task2,
  task3
};

// prototype function
void LED1_Blink(void);
void LED2_Blink(void);
void LED3_Blink(void);
int main(void)

{
    int i=task1;

    for (i=0; i<4; i++)

    switch(i)
  {
    case task1:
    {
        LED1=LED1_ON;
      LED1_Blink ();
        LED1=LED1_OFF;
    }
    break;
    case task2:
    {
            LED2=LED2_ON;
      LED2_Blink();
         LED2=LED2_OFF;
     }    
     break;
     case task3:
      {
             LED3=LED3_ON;
       LED3_Blink();
             LED3=LED3_OFF;
      }
      break;
   }

}
void LED1_Blink ()
{
    unsigned int i;
    for (i = 0; i < 1000; i++);
}
 
void LED2_Blink()
{
    unsigned int j;
    for (j = 0; j < 1500; j++);
}
 
void LED3_Blink()
{
   unsigned int k;
    for (k = 0; k < 1200; k++);
}

I know I am not good in programming and so if you find any mistake in program let me know
thanks to all of you for helping me
 
Last edited:

(*steve*)

¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd
Moderator
Jan 21, 2010
25,510
Joined
Jan 21, 2010
Messages
25,510
Vead, does your C++ have a delay () function?

Second thing. If you want the 3 LEDs to flash independently then you can't just flash them one at a time.

Try something like this

Code:
Int I=0;
Int j=0;
Int k=0;

Void main() {
  While (true) {
    I++;
    If (I > 500/2) {
      Led1on;
    } Else {
      Led1off;
      If (i > 500) {
        I = 0;
      }
    }

    /* Same for j and led2 */

    /* Same for k and led3 */
  }
 
  Delay(1);
}

The case is all mucked up because I wrote it on a phone.

Delay () I assume delays in milliseconds.

The 500 used in the comparisons should be different for each LED and represents the cycle time in ms for each LED.
 
Last edited:

vead

Nov 27, 2011
473
Joined
Nov 27, 2011
Messages
473
Vead, does your C++ have a delay () function?

Second thing. If you want the 3 LEDs to flash independently then you can't just flash them one at a time.

The case is all mucked up because I wrote it on a phone.

Delay () I assume delays in milliseconds.

The 500 used in the comparisons should be different for each LED and represents the cycle time in ms for each LED.

I use keil compiler to write c program. when I need delay generally I create delay function in program

In your example you said to use if else condition and but I don't understand how does your delay function work in program. does below example similar to example that you explained. I have not given value that you given in your example. I have write delay value in place of numbers

you mean like this examples
if delay is (200) than blink LED1
if delay is (300) than blink LED2
if delay is (400) than blink LED3
you are using 500 delay to compare other delays

Code:
   /* variables*/
   int i = 0;
   int j = 0;
   int k = 0;

int main () {


   While (1)
    i++;
   /* check  condition */
   if( i > delay_value ) {
      /* if condition is true then LED1 ON*/
       LED1=LED1_ON;
   }
   else {
      /* if condition is false than  LED2 off */
       LED1=LED1_OFF;
   }
 
    j++;
   /* check the condition */
   if( j > delay_value ) {
      /* if condition is true then LED2 ON  */
        LED2=LED2_ON;
   }
   else {
      /* if condition is false then LED2 OFF */
         LED2=LED2_OFF;
   }

     k++;
      /* check the  condition */
   if( k > delay_value ) {
      /* if condition is true then LED3 ON */
         LED3=LED3_ON;
   }
   else {
      /* if condition is false then LED3 OFF */
        LED3=LED3_OFF;
   }
 
 
 
    Delay(1);
}
 
Last edited:

Irv

Jun 7, 2017
112
Joined
Jun 7, 2017
Messages
112
OK, since it isn't a class assignment, I will try to give more help, one step at a time.
We will eventually get to the switch statement.

First, you must always be able to explain exactly what you want your program to do.
It is unreasonable to expect people to try to figure out what you want by reading code.

Let me write a description of a program, let's call it program1:

# There are 3 LED lights, numbered 1, 2, and 3.
# Step 1: I want LED 1 to turn on and blink _ times per second for _ seconds, then turn off.
# Step 2: After that, I want LED2 to turn on and blink _ times per second for _ seconds, then turn off.
# Step 3: Finally, I want LED3 to turn on and blink _ times per second for _ seconds, then turn off.
# I want to repeat steps 1 through 3 until I turn off the power.

(Fill in the blanks _ as appropriate)

Since you use the term "tasks", perhaps you mean something entirely different: Let me write another description. Call this program2. This program could make use of tasks, if you know multi-tasking;

# There are 3 LED lights, numbered 1, 2 and 3.
# I want LED 1 to turn on and start blinking _ times per second.
# While LED 1 is blinking, I want LED 2 to blink _ times per second.
# While LED 1 is blinking and LED 2 is blinking, I want LED 3 to blink _ times per second.
# All three continue blinking until I turn off the power.

(Fill in the blanks _ as appropriate)

Now, which is more like what you want to do, program1 or program2? Neither?
 

(*steve*)

¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd
Moderator
Jan 21, 2010
25,510
Joined
Jan 21, 2010
Messages
25,510
Vead, my solution lends itself to the second case above.

To avoid confusion, let's go with lrv and find out what you want to do. If it happens to be the second case then I'll explain my code further.
 

vead

Nov 27, 2011
473
Joined
Nov 27, 2011
Messages
473
OK, since it isn't a class assignment, I will try to give more help, one step at a time.
We will eventually get to the switch statement.

First, you must always be able to explain exactly what you want your program to do.
It is unreasonable to expect people to try to figure out what you want by reading code.

Let me write a description of a program, let's call it program1:

# There are 3 LED lights, numbered 1, 2, and 3.
# Step 1: I want LED 1 to turn on and blink _ times per second for _ seconds, then turn off.
# Step 2: After that, I want LED2 to turn on and blink _ times per second for _ seconds, then turn off.
# Step 3: Finally, I want LED3 to turn on and blink _ times per second for _ seconds, then turn off.
# I want to repeat steps 1 through 3 until I turn off the power.

Now, which is more like what you want to do, program1 or program2? Neither?
sorry for my late response, first I want to do program1
 

(*steve*)

¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd
Moderator
Jan 21, 2010
25,510
Joined
Jan 21, 2010
Messages
25,510
sorry for my late response, first I want to do program1

That is insufficient.

You have to tell us what you want. The example description of "program 1" includes several unknowns.

If you're not prepared to describe the requirements from scratch (which you SHOULD be able to do) then at least full in the unknown values.
 

vead

Nov 27, 2011
473
Joined
Nov 27, 2011
Messages
473
That is insufficient.

You have to tell us what you want. The example description of "program 1" includes several unknowns.

If you're not prepared to describe the requirements from scratch (which you SHOULD be able to do) then at least full in the unknown values.
my bad I thought you ware assuming any value (delay value that I wrote in program). that's why I didn't describe in requirement.

# There are 3 LED lights, numbered 1, 2, and 3.
# Step 1: I want LED 1 to turn on and blink 1000 times per second for 1seconds, then turn off.
# Step 2: After that, I want LED2 to turn on and blink 1500 times per second for 2 seconds, then turn off.
# Step 3: Finally, I want LED3 to turn on and blink 1900 times per second for 3 seconds, then turn off.
# I want to repeat steps 1 through 3 until I turn off the power.
 

Irv

Jun 7, 2017
112
Joined
Jun 7, 2017
Messages
112
Good! Now we're getting somewhere. Let me ask: do you think you will be able to see any of these LED's blinking? Or do you have some other reason for them to blink so rapidly?

To explain, any blinks faster than 18 - 20 per second are not detectable by human eyes.
 

vead

Nov 27, 2011
473
Joined
Nov 27, 2011
Messages
473
Good! Now we're getting somewhere. Let me ask: do you think you will be able to see any of these LED's blinking? Or do you have some other reason for them to blink so rapidly?

To explain, any blinks faster than 18 - 20 per second are not detectable by human eyes.
I think I understood what's wrong with my values. LED blinking was vary fast human eye can't see more than 18 - 20 per second.

# There are 3 LED lights, numbered 1, 2, and 3.
# Step 1: I want LED 1 to turn on and blink 4 times per second for 10 seconds, then turn off.
# Step 2: After that, I want LED2 to turn on and blink 6 times per second for 15 seconds, then turn off.
# Step 3: Finally, I want LED3 to turn on and blink 8 times per second for 20 seconds, then turn off.
# I want to repeat steps 1 through 3 until I turn off the power
 

(*steve*)

¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd
Moderator
Jan 21, 2010
25,510
Joined
Jan 21, 2010
Messages
25,510
Ok Vead, have you written a program to flash a single LED?

Can you post that?
 

Irv

Jun 7, 2017
112
Joined
Jun 7, 2017
Messages
112
Good. Now you need to find a delay() function that can supply our time periods.
Usually, delay(1000); will wait for 1 second (1000 ms).
Having a function such as delay() makes it much easier to get accurate timing than
trying to use for loops, because the for loop can vary with processor speed, load, etc.

For step 1, you want to turn the LED1 on, then off, every 1/4 second, for 10 seconds.

for total_time = 1 to 10 # total time for step 1 in seconds
for one_second = 1 to 4 # number of times required to blink for one second

turn on LED1; #how you do this is hardware dependent
delay(125); #wait 1/8 second (125 ms)

turn off LED1; #how you do this is hardware dependent
delay(125); #wait 1/8 second

// each time thru this loop will take 250 ms or 1/4 second.
// so you need to do it 4 times to add up to 1 second

end for one_second
end for total_time

Steps 2 and 3 would work in the same way - but no good programmer would simply write three copies of his code, and change the numbers. Ask why not.
 
Top