reading the 8 bits (separate) in a byte

Hello,

For controlling 8 outputs I'm using a 74HC595 shift register.

To control the 8 outputs separately I use bitmath:

x |= (1 << n); // forces nth bit of x to be 1. all other bits left alone.

and

x &= ~(1 << n); // forces nth bit of x to be 0. all other bits left alone.

So now I can control the 8 outputs with this code.

But how can I check the state of the outputs when I have the 8 bits (1 Byte) together?

For example:

The shift register has output 1 and 8 ON, and the rest OFF:

0b10000001

How can I check what state output 1 is in my program?

Thanks in advance,

Atmoz

if ( Value & (1 << n) )
{
  // bit n is set
}

I personally prefer a "longer" version...

if ( (Value & (1 << n)) == (1 << n) )
{
}

Thanks for your fast reply Coding Badly!!

In the meanwhile I found this at another site:

int GetBits3(byte b, int offset, int count)
{
return (b >> offset) & ((1 << count) - 1);
}

Works also great :slight_smile:

With kind regards,

Atmoz

You could use the Arduino bitRead function:

if( bitRead(x, 0) )
Serial.print(“the rightmost bit is set”)

if( bitRead(x, 7) )
Serial.print(“the leftmost bit is set”)

See: http://arduino.cc/en/Reference/BitRead

Hmzz, then I get

error: 'bitRead' was not declared in this scope

I think I've to declare something.
I check this tomorrow... (here in the Netherlands it's bedtime) goodnight :wink:

Thanks for all the (fast) help!!

Greetz,

Atmoz

I think I've to declare something.

I think it's what version of the Arduino IDE you are using. Bit commands were added around version ?

Lefty

I think it's what version of the Arduino IDE you are using. Bit commands were added around version ?

Lefty

0010 Alpha...

I think I should download Arduino 0017 ;D
Is it downwards compatible with the version I have?

With kind regards,

Atmoz

[edit]

No, it's not compatible :-/

I get this error:

C:\Users\Gebruiker\Downloads\arduino-0017\arduino-0017\hardware\cores\arduino/wiring.h:125: error: expected ',' or '...' before numeric constant

In function 'void sendByteOut(int)':
Bad error line: -12