Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Defining single bit variables in Microchip C18

Status
Not open for further replies.

Nemesis77

Newbie level 3
Joined
Feb 20, 2009
Messages
3
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Location
South Africa
Activity points
1,301
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.
 

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.
 
microchip c18

Thanx btbass. This is a great answer and even beter than I actualy needed.
 

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.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top