Switch statements

Jul 15, 2018 at 10:03am
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 Jul 15, 2018 at 10:08am
Jul 15, 2018 at 1:44pm
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?

Jul 15, 2018 at 3:35pm
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.
Jul 15, 2018 at 11:27pm
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!
Jul 16, 2018 at 12:35am
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.