piątek, 21 października 2011

How to read a bit state? [AVR programming]

You can accomplish this in two simple ways - by using special functions like bit_is_set(Register,Bit number) / bit_is_clear(Register, Bit number) or by using some basic boolean algebra. First function  examines whether a bit is set, it returns a non-zero value if true. Second, works quite similar – it returns  zero when a bit is set, other values if it has been deleted. When using Boolean algebra, a basic knowledge of ANSI C programming is needed. This way is highly recommend, because any external library isn’t required – just regular C syntax.

Take a look at those examples:
// Check if a third bit of PORTD register is high 
//(instruction below return true if so)
bit_is_set(PORTD,3); // first option
PORTD & (1 << 3); // second option 
How does it works?
Let’s assume that PORTD looks like 11011010. There is high state on pins 1,3,4,6,7 and low on the rest.  If we want to check if pin 3 is active (high state) we must perform left bit shifting like 1 << 3 and examine the logical conjunction of those two.  

    11011010
& 00001000
    00001000

Which equals to decimal 8 (non-zero) – that means the third bit is set.

Brak komentarzy:

Prześlij komentarz