cancel
Showing results for 
Search instead for 
Did you mean: 

>> or & operators

Jalal Sadigli
Associate III
Posted on May 09, 2017 at 22:28

hi

this code which i use >> (shift operator) to detect flag work correctly

void putchar( char *string)

{

while(*string)

{

while(usart_sr >> 6 == RESET);

while(usart_sr >> 7 == RESET);

USART_SendData(USART2,*string);

*string++;

}

}

but when i change it from & and some value of hex, the does not work correctly

void putchar( char *string)

{

while(*string)

{

while(usart_sr & 0x80 == RESET);

while(usart_sr & 0x40  == RESET);

USART_SendData(USART2,*string);

*string++;

}

}

is there someone to explain why?

thanks

#flagselect ##operators
4 REPLIES 4
Posted on May 10, 2017 at 00:01

The bit shift doesn't do what you think it does, and you should also use brackets to be more explicit about ordering

while((USART2->SR & 0x80) == RESET);

I don't know where you get usart_sr from but USART2->SR is volatile so the compiler will always re-read it regardless of optimization level.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
alfbaz
Associate II
Posted on May 10, 2017 at 06:55

Also, assuming usart_sr is some byte value and bits 6 or 7 are set, in the first example you are shifting them to the LSB and seeing if it's equal to RESET which presumably equals 1

In the second example, firstly you have reversed the order in which the bits are tested. 0x80 is the seventh bit and 0x40 is the 6th. Secondly if these bits are set you will end up with values 0x80 and 0x40 in each statement which, judging from example 1, cant equal RESET.

If you want to wait while bit 7 is set

while(usart_sr & 0x80);

If you want to wait while bit 7 is clear

while(!(usart_sr & 0x80));

Posted on May 10, 2017 at 06:40

Sorry,Ä° have forgotten to mention what is usart_sr .

Usart_sr is just uint32_t pointer to SR register of usart2

Posted on May 10, 2017 at 16:09

RESET in this case will be zero.

The SR is at least 16-bit wide, shifting it does not extract singular bits.

If usart_sr is a pointer you'd presumably want to use *usart_sr to read the content of the pointer rather than act on the value of the pointer itself (ie the address)

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..