View previous topic :: View next topic |
Author |
Message |
rovtech
Joined: 24 Sep 2006 Posts: 262
|
Naming a bit out of a byte |
Posted: Thu Jun 14, 2012 9:04 am |
|
|
I want to name a bit out of a byte.
If ‘switches’ is the 8 bit byte and ‘camera’ is the first bit 0 then I want to test whether the camera is turned on as in:
The following works:
Code: | #define camera 0x01
switches = port_b;
if (switches & camera) {etc} |
but the code is not as easy to understand. A structure would also work but the variable name would be switches.camera
I tried the following from something I saw but it does not work. I can't find anything like this in my C books.
Code: | char switches; // console switches
#define camera (switches, 0) // camera switch, bit 0 of switches
if (camera) {etc} |
It seems such a dumb and simple thing. |
|
|
temtronic
Joined: 01 Jul 2010 Posts: 9217 Location: Greensville,Ontario
|
|
Posted: Thu Jun 14, 2012 9:25 am |
|
|
Hint:
If you press F11 while your project is open, the CCS HELP files will appear...just search, scroll, mouse over to the appropriate section.
Also if you open up some of the examples that CCS kindly supplies, you'll see how they do almost everything you want or need to do ! |
|
|
jeremiah
Joined: 20 Jul 2010 Posts: 1342
|
|
Posted: Thu Jun 14, 2012 10:32 am |
|
|
I would suggest a union of a byte and 8 bits together. You can load the whole port into the byte version and access the individual bits:
Code: |
typedef union{
unsigned int8 byte;
struct{
unsigned int8 b0 : 1;
unsigned int8 b1 : 1;
unsigned int8 b2 : 1;
unsigned int8 b3 : 1;
unsigned int8 b4 : 1;
unsigned int8 b5 : 1;
unsigned int8 b6 : 1;
unsigned int8 b7 : 1;
} bits;
} u8;
#define camera bits.b0
|
Then do something like:
Code: |
u8 switches;
switches.byte = port_b;
if(switches.camera){
//blah
}
|
|
|
|
rovtech
Joined: 24 Sep 2006 Posts: 262
|
Solution found |
Posted: Thu Jun 14, 2012 11:21 am |
|
|
Not very helpful temtronic
Thanks for the reply jeremiah, yes that will work but not what I wanted.
I found what I want after going through books on C and examples.
I must have passed #bit in the CCS manual a dozen times.
This is what I was looking for:
Code: | char console_switches;
#bit camera=console_switches.0
#bit var2=console_switches.1 // etc for all bits
if (camera) {code} // test switch "camera" |
|
|
|
temtronic
Joined: 01 Jul 2010 Posts: 9217 Location: Greensville,Ontario
|
|
Posted: Thu Jun 14, 2012 2:20 pm |
|
|
Not very helpful ???
There are at least 6 examples that CCS supplies in the examples folder as well as in the manual that do exactly what you requested....
Yes, it does take a few minutes of reading BUT then you will KNOW where to look and HOW it works inseaed of just copying from someone else's code snippet. |
|
|
|