Main Site Documentation

Register Access Problem


#1

I’m using the Cerbuino Bee with STM32F405 microcontroller.
I’m trying to set bit 31 to a 1 in a register in a 32bit register with this code:
MyReg.SetBits(1<<31);
Which gives me an error: cannot convert from int to uint
But the following line works just fine:
MyReg.SetBits(1<<30);
Why can’t I set bit 31 to a 1?
Please let me know what I’m going wrong.
Thanks


#2

try casting everything into UINTs (kinda like the error says :wink: ). Why is 31 important, in a 32-bit integer ? :whistle:


#3

Bit 31 is the 32nd bit in a GPIO configuration register. Can you please provide a code snippet. to correctly set bit 31 to 1? I’d really appreciate it.
Thanks


#4

Nevermind. Simon’s got your back :slight_smile:

I’d just confuse you.


#5

#6

The trouble is,

MyReg.SetBits((uint)(1<<31));

…doesn’t compile. VS suggests using the Unchecked keyword:

           
unchecked
{
   MyReg.SetBits((uint)(1 << 31));
}

Is this correct?

EDIT: Brett’s solution works


#7

SetBits(1<<0) sets bit 0 to a 1 correct? Bit 0 is the first bit in a 32 bit register, correct?
SetBits(1<<31) should set bit 31 to 1. Bit 31 is the last bit in a 32 bit register, correct? This is how the ST reference manual shows it anyways.
So why do I get an syntax error for SetBits(1<<31)?
Can someone please provide the correct syntax?
Thanks


#8

That wasn’t why I said the tongue in cheek comment, and yeah I could have helped more first up. The fact that the <<30 worked and the <<31 didn’t, along with the error, should have helped note the need to do a UINT casting.


#9

SetBits((uint)(((uint)1)<<31)) should be enough brackets to do it. The 1 needs to be a UINT otherwise it’s interpreted as a sign bit and << will not work as expected.


#10

Thanks guys
Using mtylerjr’s way with unchecked works and Simon’s way works too.
Is this because of the << shift operator operating on the last bit or something? I’ve looked around some basic programming manuals and they don’t explain why you need to use a shift operator to change a bit in a register. Dumb question. Why is it necessary to use the shift operator in this case?
Thanks


#11

The error you saw is because silently, the 1<<30 was cast into a UINT.

Breaking it down:
1 is treated as an INT. The shift result is an INT. Then SetBits needs a UINT and it’s silently casting INT to UINT for you.
When doing 1<<31, this is a negative number in an INT, and you can’t silently cast it to a UINT, and the error is thrown.

In my cast example, you’re making sure the 1 is treated as a UINT from the outset, and no chance of confusion.


#12

@ tdcooper33 - As a short-hand you can use the numeric suffix ‘u’ to ask the compiler to treat the numeric literal as a uint rather than an int.

The following should do the trick


SetBits(1u << 31);