Julian F. Weinert
Julian F. Weinert

Reputation: 7560

AVR setting output repeatedly toggles the pin

I'm writing a firmware for an ATMega328 and facing some issues. After searching in my logic for hours I could boil the code down to the most basic example and still have the problem.

I'm setting a pin to the value of a variable. Because I don't want to store to copies of a big array I'm setting the pin to the same value over and over again and if the variable changes, the pin gets set to a different state.

int main() {
    DDRB |= _BV(PB2);

    while (1) {
        PINB |= _BV(PB2);
        _delay_ms(50);
    }

    return 0;
}

The problem is that with this code the pin toggles on and off every 50ms.

I could think of restructuring my code so I can detect change of the mentioned variable without the need of a copy. But in the end I don't understand the problem, because I'm setting a bit of the output port to the same value over and over again.

Upvotes: 0

Views: 574

Answers (1)

ReAl
ReAl

Reputation: 1301

PINB is input register (output register is PORTB).

And yes, writing 1 to input register PINx toggle bit in corresponding output register PORTx and pin value in modern (almost all for now) AVRs.

Upvotes: 2

Related Questions