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
Then the UNION variant
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;
}
}
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;
}
}