Need some help with _BV() macro

Status
Not open for further replies.

borge

Junior Member level 1
Joined
Jan 4, 2013
Messages
16
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Location
Norway
Visit site
Activity points
1,375
Hi

Have been reading up on Pogramming, and starting to understand some basics.
I got a problem when i wanted to add more ports to this easy tutorial.

When i added the _BV(PD5), this was the only led blinking, not both. how do i configure this.
Do i need to define the pins separately ?
I have searched the net, but not any clear answers.
I used Programmers notepad.

Code:
#include <avr/interrupt.h>
#define F_CPU 100000UL
#include <util\delay.h>

int main() 
{

DDRD = _BV(PD4);           // this is the original
DDRD = _BV(PD5);           // i added this

while(1) {

PORTD = _BV(PD4);
_delay_ms(1000);

PORTD  &= ~_BV(PD4);
_delay_ms(1000);

PORTD = _BV(PD5);                  // The PD5 i added
_delay_ms(1000);

PORTD &= _BV(PD5);
_delay_ms(1000); 

}
   return (0);
}
 

_BV(x) is the equivalent of (1<<x)

When you use
Code:
DDRD = _BV(PD4);           // this is the original
DDRD = _BV(PD5);           // i added this

it is the equivalent of
Code:
DDRD = 0b00010000;
DDRD = 0b00100000;

So you assign a value and then another value so only the last value stands

In order to preserve the value and set another bit you have to use the OR operator
Code:
DDRD = _BV(PD4);
DDRD |= _BV(PD5);      // the equivalent of DDRD =  DDRD | _BV(PD5);

Even better is to do this
Code:
DDRD = _BV(PD5) | _BV(PD4);

- - - Updated - - -

You should apply OR in a similar manner when you set the port
Code:
PORTD = _BV(PD5);                  // this assigns 0 to all bits except from bit 5

Use this instead
Code:
PORTD |= _BV(PD5);                  // keep the current value and in addition set bit5
 
Reactions: borge

    borge

    Points: 2
    Helpful Answer Positive Rating
Thanks alexan_e.

Will try this evening.

When i use this, and configuring two ports or more, do i continue with the
Code:
PORTD [COLOR="#FF0000"]|[/COLOR]= _BV macro  //for each port

And keep the first without th OR Operator
PORTD = _BV(PD4);
Code:
PORTD |= _BV(PD5);                  // keep the current value and in addition set bit5
 

Reactions: borge

    borge

    Points: 2
    Helpful Answer Positive Rating
Thanks alexan_e

your help did the trick. and i read from the link you gave me.

i used both the _BV macro, and 0b1000000; way to test, varied the delay and played around with it.

:smile:
 
Last edited:

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…