Forum: µC & Digital Electronics controll only 1 bit from 1 byte

Author: micro u. (Guest)
Posted on:

Rate this post
0 useful
not useful
AVR Studio - ATmega8 - myAVR.de MK2 Board

im learning to switch 2 leds on and off.

my problem: how can i control only 1 bit of the whole port?
DDRC = 0xFF;
PORTC = 0x01; // Turn LED 1 on
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

Author: Floh (Guest)
Posted on:

Rate this post
0 useful
not useful
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

Author: user (Guest)
Posted on:

Rate this post
0 useful
not useful
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;


Entering an e-mail address is optional. If you want to receive reply notifications by e-mail, please log in.

Rules — please read before posting

  • Post long source code as attachment, not in the text
  • Posting advertisements is forbidden.

Formatting options

  • [c]C code[/c]
  • [avrasm]AVR assembler code[/avrasm]
  • [code]code in other languages, ASCII drawings[/code]
  • [math]formula (LaTeX syntax)[/math]

Bild automatisch verkleinern, falls nötig
Note: the original post is older than 6 months. Please don't ask any new questions in this thread, but start a new one.