controll only 1 bit from 1 byte

Guest #3027556
AVR Studio - ATmega8 - myAVR.de MK2 Board

Hi
im learning to switch 2 leds on and off.

my problem: how can i control only 1 bit of the whole port?
1
DDRC = 0xFF;
2
PORTC = 0x01; // Turn LED 1 on
3
PORTC = 0x02; // Turn LED 2 on

The problem: the second i turn on number 2, i also turn off number one.

Is there a way of saying Byte.Bit, or PORTC.firstBit


thanks for your help
Guest #3027560
You can do this with bit manipulation, and, or, exor.

PORTD |= (1<<PD0); // sets PD0
PORTD &= ~(1<<PD0); // clears PD0
PORTD ^= (1<<PD1); // toggles PD1
Guest #3027563
you can use this

struct bits {
  uint8_t b0:1;
  uint8_t b1:1;
  uint8_t b2:1;
  uint8_t b3:1;
  uint8_t b4:1;
  uint8_t b5:1;
  uint8_t b6:1;
  uint8_t b7:1;
} __attribute__((_packed_));

#define SBIT_(port,pin) ((*(volatile struct bits*)&port).b##pin)
#define SBIT(x,y) SBIT_(x,y)

SBIT(PORTC,0) = 0;
SBIT(PORTC,1) = 1;

Reply

A question of your own? This thread is over 13 years old. Ask it in a thread of its own – more people read along there, and it gets answered more often and sooner.

Start a new thread

A fix, an addition or feedback on this thread? Then reply here.

Formatting
  • [c]C-Code[/c]
  • [code]code in other languages, ASCII drawings[/code]
  • [math]formula (LaTeX syntax)[/math]
  • [[Title]] – link to an article
  • Link to another post: right-click its post ID (#8078628), copy the address, paste it into the text

More about formatting

Post long source code as an attachment, not in the text.

Already registered? Log in

Not shown to anyone. We send you a link; your post appears once you confirm it there.

By submitting you create a free account and accept the terms of use.