Pages: [1]   Go Down
Author Topic: read specific bits of a byte?  (Read 442 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 33
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I am reading in a single byte over TWI.  Each bit stands for something.  I want to be able to read that byte into a data structure, then be able to reference each bit.  I had thought of something like this

struct {
  uint8_t key1:1;
   uint8_t key2:1;
   uint8_t key3:1;
   uint8_t key4:1;
   uint8_t key5:1;
   uint8_t key6:1;
   uint8_t key7:1;
   uint8_t key8:1;
} keys;

structs keys mykeys;

mykeys = SOME BYTE I HAVE.

Serial.print(mykyes.key1);  // would print a zero or one.

But the above doesn't work.  I think I an misunderstanding how struct works.  Anyone have any thoughts on what would be the simplest way to get the value of each bit?

thanks
chad
Logged

Austin, TX
Offline Offline
Jr. Member
**
Karma: 1
Posts: 94
Shh! I am hunting wabbit. Killlll the wabbit!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

I would use something like the following to test a given bit specified by n where 0 <= n <= 7

value = (keys >> n) & 1;

With this expression value will be either 0 or 1 depending upon what the bit contained.
Logged

0
Offline Offline
Full Member
***
Karma: 0
Posts: 203
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

tempalte has got a lot of the right parts, just not all together.

The packed bitfield structure is correct. That will let you access the 8 bits of the byte individually. But if you want to assign a byte into it, then you either need to put it inside a union or do some typecasting.

For whatever reason, it is not the habit of Arduino programmers or the avr-gcc people to use bit structures. They tend to shift and mask. At a first glance, the object code is about the same so it is a matter of preference.  (Personally, I like bit structs for fixed structures, but I don't code that way here.)
Logged

Pages: [1]   Go Up
Jump to: