"Or"ing DDRB with itself

Status
Not open for further replies.

cosmonavt

Member
According to a video tutorial I saw somewhere, here's the code for a blinking LED:

Code:
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
	DDRB = DDRB | 0b00000001;
	
    while(1)
    {
		PORTB = 0b00000000;
		_delay_ms(100);
		PORTB = 0b00000001;
		_delay_ms(100);
   }
}

Why do we have to say
Code:
DDRB = DDRB | 0b00000001;
in the beginning of the int function?

Does this mean that during the program, DDRB can accept values of either 0b00000000 or 0b00000001? Is DDRB set to 0b00000000 by default?
 
Last edited:
I'm not familiar with AVR programming, so what follows may be rubbish:-
I assume the LED is attached to PORTB bit 0.
1) that line seems to be just ensuring that bit 0 of register DDRB (data direction?) is set to 1 (output?).
2) the while loop seems to keep PORTB bit 0 at 1 and all the other bits at 0. How's that supposed to blink a LED?
Is DDRB set to 0b00000000 by default?
The datasheet for the AVR should tell you.
 
Oh sorry there was an error in code, corrected it. It should be as follows:

Code:
		PORTB = 0b00000000;
		_delay_ms(100);
		PORTB = 0b00000001;
		_delay_ms(100);
 
You're ORing with 1, not with itself. ORing with 1 sets the bottom bit and makes it output.

Mike.
 
Why OR it anyway? Why not simply make it DDRB = 0b00000001?

You could if you knew that 0b00000001 was what you wanted. ORing preserves the direction of other bits. For example if DDRB was 0b00000100 ORing it with 0b00000001 gives 0b00000101.
 
Last edited:
Thanks. It means that it will ease out the process of preserving other bits. Like if we want the pin 2 to change to output, we can simply type 0b00000100 instead of repeating the direction of pin 0 again and again, i.e. 0b00000101

Am I right?
 
Thanks. It means that it will ease out the process of preserving other bits. Like if we want the pin 2 to change to output, we can simply type 0b00000100 instead of repeating the direction of pin 0 again and again, i.e. 0b00000101

Am I right?


thats right....

I use some other method... I use,
sbi(DDRB,2)
or
cbi(DDRA,0)
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…