A case of RTFM - bitSet

Hi,
This might save someone some time.

I am using bit flags to control access to shared variables between the loop function and interrupt service routines. To make my code as beginner friendly as possible I used the bit functions (bitSet,bitRead,bitWrite,bitClear).

Everything works fine for my first 3 variables, but the 4th is never accessible.

The reason is very simple and if I had been paying attention I would have spotted it hours ago. The Arduino bit functions quite reasonably regard the bits in a byte as numbered 0-7, so there is no bit 8 to set.

Its obvious enough, but if you are used to using bits directly through powers of 2, you like me will have a problem.

RTFM

Duane B

rcarduino.blogspot.com

Same thing with arrays...

If you have a 10-element array and you read Array[10], you are reading something random/unknown beyond the array which holds elements 0 thru 9. Worse, if you write beyond the end of the array screwy thingc can happen and you can even crash your program!

P.S.
If you always start counting at "zero', you might be a programmer! :smiley: ...How many kids do you have? "Four", "0, 1, 2, 3"

if you are used to using bits directly through powers of 2, you like me will have a problem.

:
Not sure what you mean there
20 = 1= 0x01
27 = 128 = 0x80

Hi,
Cut a long story short, I was using bit flags like so

#define CHANNEL_ONE 1
#define CHANNEL_TWO 2
#define CHANNEL_THREE 4
#define CHANNEL_FOUR 8

Without paying enough attention to the function I was calling bitSet(n,CHANNEL_FOUR) which instead being equivalent to -

n |= 8

was actually equivalent to

n |= (1<<8)

which overflows my byte.

Moderator edit: eliminated smileys

That was the first time I have used the Arduino bit functions, I am going back to bitwise operators.

Duane B

rcarduino.blogspot.com

Cut a long story short, I was using bit flags like so

#define CHANNEL_ONE 1
#define CHANNEL_TWO 2
#define CHANNEL_THREE 4
#define CHANNEL_FOUR 8

Without paying enough attention to the function I was calling bitSet(n,CHANNEL_FOUR) which instead being equivalent to

Why not simply assign CHANNEL_N proper values - 0, 1, 3, and 7?