| Author |
Message |
Nemesis77
Joined: 20 Feb 2009 Posts: 3 Location: South Africa
|
11 May 2009 10:56 bit z charu c18 |
|
|
|
|
I want to define flags in my code. In assembler I used to do it as follows:
flags equ 0x020 ; Define variable
#define flag0 flags,0 ; Flag0
#define flag1 flags,1 ; Flag0
etc.
How would I do this in C18. i.e. I want to define a CHAR variable and I want to be able to set or clear each bit of the 8bit CHAR variable. C18 has some predefined for example... INTCONbits.GIE = 1; This statement sets only 1 bit in the INTCON register.
|
|
| Back to top |
|
 |
btbass
Joined: 20 Jul 2001 Posts: 1267 Helped: 115 Location: Oberon
|
11 May 2009 17:49 c18 bits |
|
|
|
|
You use bitfields.
| Code: |
/*--- Relay Structure ---*/
struct RELAYBITS
{
unsigned rca:1; /* SEL_UNBAL relay */
unsigned earth:1; /* EARTHSEL relay */
unsigned ground:1; /* GND_RLY relay */
unsigned phase:1; /* Phase invert relay */
unsigned bridge:1; /* Mono amplifier mode */
unsigned dummy:2; /* Alignment bits */
unsigned mute:1; /* MUTE relay */
};
/*--- Relay bits union ---*/
typedef union
{
struct RELAYBITS Bits;
unsigned char data;
}RELAY;
volatile RELAY RELAYbits;
|
You can set and clear the bits like this:
| Code: |
RELAYbits.data = 0; /* Clear all bits */
RELAYbits.Bits.ground = 0; /* Clear single bit */
RELAYbits.Bits.rca = 1; /* Set a bit */
|
Bit fields dont have to be single bits, you could define a bitfield with 3 bits, or any number of bits
| Code: |
typedef struct
{
unsigned threebits : 3;
unsigned twobits : 2;
}BITS,
volatile BITS Bits;
Bits.threebits = 7;
Bits.twobits = 3;
|
then you could set them to any value between 0 and the maximum value the bits can hold.
|
|
| Back to top |
|
 |
Nemesis77
Joined: 20 Feb 2009 Posts: 3 Location: South Africa
|
11 May 2009 23:01 microchip c18 |
|
|
|
|
| Thanx btbass. This is a great answer and even beter than I actualy needed.
|
|
| Back to top |
|
 |
Google AdSense

|
11 May 2009 23:01 Ads |
|
|
|
|
|
|
| Back to top |
|
 |
btbass
Joined: 20 Jul 2001 Posts: 1267 Helped: 115 Location: Oberon
|
16 May 2009 19:38 mcc18 bit field |
|
|
|
|
| Look at the Pic18F header files. They make extensive use of bitfields. You can learn a trick or two by studying the header files.
|
|
| Back to top |
|
 |