5

I'm currently working on a project where I read a 32 bit sequence. The digitalPin is always HIGH when no sequence is received and starts oscilating with about 1kHz when the sequence starts (RC5).

I am setting and clearing bits of an uint32_t depending on which signal is on the digitalPin. It seems to work very well with every bit except of the MSB.

Here a short code snippet to show what I mean:

const short irPin = 8;
const short msgDelay = 250;
uint32_t data = 0xFFFFFFFF;
long msgArrived = 0;
void setup(){
 Serial.begin(115200);
 pinMode(irPin, INPUT);
}
void loop(){
 long now = millis();
 if( (!(PINB & 1)) && ((now - msgArrived)> msgDelay)){
 msgArrived = millis();
 bitClear(data, 31);
 Serial.println(data, BIN);
 }
}

This gives me an output of

11111111111111111111111111111111

I have already tried

bitClear(data, 32); -> 11111111111111111111111111111111
bitClear(data, 30); -> 10111111111111111111111111111111

So every output is right, but not the when I try to clear the msb.

Has anyone experienced a similar behaviour?

asked Jun 17, 2016 at 15:41
3
  • 1
    bitClear(data, 31); should be the msb of the uint32_t. bitClear() goes from 0 - sizeof(uint32_t)-1. And with bitClear(data, 32); I only tried if the documentation lied to me. Commented Jun 17, 2016 at 16:24
  • sorry missed a part of code on first comment, does it work if you make it "manually" with data &= ~(0x1 << 31) ? Commented Jun 17, 2016 at 16:41
  • 1
    yes this works, but look at the answer by BrettAM. I missed out, that println() doesn't print leading zeros. Commented Jun 17, 2016 at 16:50

1 Answer 1

5
uint32_t data = 0xFFFFFFFF;
Serial.println(data, BIN);
data = 0xFFFFFFFF;
bitClear(data, 30);
Serial.println(data, BIN);
data = 0xFFFFFFFF;
bitClear(data, 31);
Serial.println(data, BIN);

On my mega outputs:

11111111111111111111111111111111
10111111111111111111111111111111
1111111111111111111111111111111

Are you sure you aren't mistaking the fact that println doesn't print leading 0's for the number being nothing but 1's? Try printing as hex, then all the numbers will be the same width:

FFFFFFFF
BFFFFFFF
7FFFFFFF
answered Jun 17, 2016 at 16:45
1
  • 2
    I fact i actually did miss out the fact, that println doesn't print leading zeros. Thanks. Would +1, but I am missing reputation for that. Commented Jun 17, 2016 at 16:51

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.