Switch statements

Hello everyone, I would like to rewrite this function in a different format using switch statements.

Q1 - Is it practical in this example using switch statements?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  void updateLEDs(void){
		while(!TRMT);
		TXREG = gBuffer1[0];
		while(!TRMT){};
		TXREG = gBuffer1[1];
		while(!TRMT){};
		TXREG = gBuffer1[2];
		while(!TRMT){};
		TXREG = gBuffer1[3];
		while(!TRMT);
		LE = 1;
		NOP();
		NOP();
		NOP();
		LE = 0;
}


Switch statements example

Q2 - Is the code posted below correct? (behaviour of the LEDs that are being driven is different, they skip..)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  void updateLEDs(void){
	
	static int byte = 0;
	while(!TRMT);
	
	switch(byte)
	{
		case 0: TXREG = gBuffer1[0];	while(!TRMT){};	break;
		case 1: TXREG = gBuffer1[1];	while(!TRMT){};	break;
		case 2: TXREG = gBuffer1[2];	while(!TRMT){};	break;
		case 3: TXREG = gBuffer1[3];	while(!TRMT){};	break;
		
		default: break;
	}
	
	if (++byte > 3){ 
		LE = 1;
		NOP();
		NOP();
		NOP();
		LE = 0;
		byte = 0; 
	}
	
}
}
Last edited on
For what I can see, those two codes make totally different things.

In you first example, TXREG, whatever it is, is assigned with a differet value every time TRMT becomes false. Later, LE becomes 1, NOP() is invoked three times, LE is turned into 0, and the function ends.

In your second example, TXREG is assigned with the value of gBuffer1[0] once, then the function exits.

Am I wrong?

This makes more sense, i guess:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
void updateLEDs(void){
	
	static int byte = 0;
	while(!TRMT);
	
	while(byte<4){
            switch(byte)
	{
		case 0: TXREG = gBuffer1[0];	while(!TRMT){};	break;
		case 1: TXREG = gBuffer1[1];	while(!TRMT){};	break;
		case 2: TXREG = gBuffer1[2];	while(!TRMT){};	break;
		case 3: TXREG = gBuffer1[3];	while(!TRMT){};	break;
		
		default: break;
	}
         byte++;
        }
	
	if (byte > 3){ 
		LE = 1;
		NOP();
		NOP();
		NOP();
		LE = 0;
		byte = 0; 
	}
	
}
}

Although, i don't understand why do you want to do that, because it just looks redundant to me atleast.
Enoizat and helpinghand, I agree with both of you. I decided to stick with the first piece of code. Switch method is not that necessary. Thank you for your help!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void
wait_until_TSR_empty() // or whatever
  while (!TRMT)
    /* do nothing */;
}

void
updateLEDs(void)
{
  wait_until_TSR_empty(); 

  for (int i = 0 i < 4; ++i) {
    TXREG = gBuffer1[ i ];
    wait_until_TSR_empty();
  }

  LE = 1;
  NOP(); NOP(); NOP();
  LE = 0;
}
Topic archived. No new replies allowed.