I have a few doubts about some code lines in AVR

DDRB |= (1 << 0);

PORTB ^= (1 << 0);

What’s the difference between

^= and =

|= and =

&= and =

Thanks for helping me

I have a few doubts about some code lines in AVR

DDRB |= (1 << 0);

PORTB ^= (1 << 0);

What’s the difference between

^= and =

|= and =

&= and =

Thanks for helping me

google "^= operator c++"

so for example let me see if i could under stand

a^=b

then

a XOR b

ab a

00 0

01 1

10 1

11 0

That's it??

a|=b

a AND b

ab a

00 0

01 0

10 0

11 1

a OR b

ab a

00 0

01 1

10 1

11 1

Yes, and "a &= b;" is just equivalent to "a = a&b;", for example.

In the code lines you’ve mentioned, the intention is to modify bit0 in the registers:

^= (1 << 0) will toggle bit0

|= (1 << 0) will set bit0

&= (1 << 0) will clear bits 1-7

Thanks for the help

These are operators in the C++ programming language. Go read at a C++ tutorial - just google "cpp tutorial" and have a look at the section on assignment operators.

aurquiel:

I have a few doubts about some code lines in AVRDDRB |= (1 << 0);

PORTB ^= (1 << 0);What’s the difference between

^= and =

|= and =

&= and =Thanks for helping me

The “^” operator means “exclusive OR”, the “|” is OR and the “&” is AND.

Sticking them together with an equal sign just saves a bit of typing. For example:

this: DDRB |= (1 << 0);

means the same thing as this: DDRB = DDRB | (1 << 0);

this: PORTB ^= (1 << 0);

means the same thing as this: PORTB = PORTB ^ (1 << 0);

even this: x += 3;

means the same thing as this: x = x + 3;

Using a tilde (~) character is useful for clearing bits. For example, to SET bit 2 in a register:

REG |= _BV(2); ← see note near the bottom

To CLEAR the bit:

REG &= ~_BV(2);

You could do it the hard way and say this:

REG &= 0xFF - _BV(2);

…but why when the tilde is easier?

NOTE: “_BV(n)” is a macro which expands bit numbers to bit values. For example, “_BV(4)” means “the value of bit 4” which is decimal 32, hex 0x20.

You can use multiples ones too:

REG |= (_BV(2) | _BV(4)); // set bits 2 and 4 high

REG &= ~(_BV(2) | _BV(4)); // clear bits 2 and 4 low