Bit shift and masking for PORTB not working?

Go To Last Post
6 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I would like to control a LED on PB0. For the sake of readable code I would prefer to activate the IO port with this line of code:

PORTB |= (1<<PORTB0);

However this doesn't seem to work and I don't understand why.

I realize I could set PORTB to 0xfe to activate PB0 but I prefer using the bit and shift masking scheme for clarity.

Thanks.

ATmega16
AVRStudio4
GCC compiler

Last Edited: Wed. Apr 21, 2010 - 01:32 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Have you set it as an output beforehand (DDRB)?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0
PORTB |= (1<<PORTB0);

Quote:
I realize I could set PORTB to 0xfe to activate PB0
But these two things are not the same. First it should be set to 0x01, not 0xfe. Second, the line of code affects only the one bit, the other affects all bits of the port.

Regards,
Steve A.

The Board helps those that help themselves.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Yes, I set the DDRB register as an output.

I didn't mention that I am using the STK500. I need to set PB0 low to drive the LED, hence the 0xfe.

I might have just answer my own question but is the answer:

PORTB |= (0<<PORTB0)

?

I could swear I tried that. I'll check it when I get home.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Quote:
I might have just answer my own question but is the answer:

PORTB |= (0<<PORTB0)


Nope, that line does nothing. Try:

PORTB &= ~(1 << PORTB0);

Regards,
Steve A.

The Board helps those that help themselves.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thank you

PORTB &= ~(1 << PORTB0);

worked.