What is the best coding practice

Thread Starter

t06afre

Joined May 11, 2009
5,934
I am using HI-Tech PICC16. I am also quite new to C and microcontrollers only a few months. Then it comes to bit operations included testing on a variable. I found the whole thing somewhat awkward. As C is not very good at such operations. We can use macros but I do not like that concept. I think it obscure the code. So I came up with using UNION. To illustrate I have made two code examples. Both compile to the exact same machine code. But then it comes to coding practice which one is best or most easy to understand. If you saw the code for the first time.
First the macro variant
Rich (BB code):
 define _XTAL_FREQ 4000000
#include <htc.h>
#define bitset(var, bitno) ((var) |= 1UL << (bitno))
#define bitclr(var, bitno) ((var) &= ~(1UL << (bitno)))
#define toggle_bit(var,bitno) (var ^= (1UL << bitno))
#define test_bit(var,bitno) (var & (1UL << bitno)) 
#define  DISP_EN 0
#define  DISP_RS 1
#define  DISP_RW 2
char unsigned test_var; 
char unsigned LCD;
void main(void)
{
 LCD=0x00;
 test_var=0x00;
 TRISC=0;
 while(1)
  {
   LCD=240;
   test_var=240;
   bitset(LCD, DISP_EN);
   bitset(LCD, DISP_RW);
   bitset(LCD, DISP_RS);
    if (test_bit(LCD, DISP_RS)) 
     {(bitclr(LCD, DISP_EN);}
   PORTC=test_var;
   PORTC=LCD;
  }
}
Then the UNION variant
Rich (BB code):
 #define _XTAL_FREQ 4000000
#include <htc.h>
char unsigned test_var; 
union { 
   char unsigned data;
  struct {
  unsigned  DISP_EN:1;
  unsigned  DISP_RS:1;
  unsigned  DISP_RW:1;
    }flags;
}LCD;
void main(void)
{
 LCD.data=0x00;
 test_var=0x00;
 TRISC=0;
 while(1)
  {
   LCD.data=240;
   test_var=240;
   LCD.flags.DISP_EN=1;
   LCD.flags.DISP_RW=1;
   LCD.flags.DISP_RS=1;
    if (LCD.flags.DISP_RS) 
     {LCD.flags.DISP_EN=0;}
   PORTC=test_var;
   PORTC=LCD.data;
  }
}
 

eblc1388

Joined Nov 28, 2008
1,542
Isn't the answer obvious?

Some programmers have already been doing that all the times.

Just so you wonder why someone would read the ADCH result into an integer and then shift it eight times before adding the ADCL result to get the full 10-bit result.

UNION...UNION...UNION.
 

Thread Starter

t06afre

Joined May 11, 2009
5,934
Isn't the answer obvious?

Some programmers have already been doing that all the times.

Just so you wonder why someone would read the ADCH result into an integer and then shift it eight times before adding the ADCL result to get the full 10-bit result.

UNION...UNION...UNION.

UNION...UNION...UNION.[/QUOTE]
Thank you for the answer. I could not find any note of it in the PICC manual, or the web. And I am quite new to C.
By the way will this be the correct setup for parseing the ADC data into a unsigned int
Rich (BB code):
union { unsigned int RESULT; unsigned char DATA[sizeof(unsignned int)]; } CONV; //later in the code CONV.DATA[0]=ADRESL; CONV.DATA[1]=ADRESH; CONV.RESULT++;
 
Top