Search code examples
cmicrocontrolleratmegaatmel

When programming my Atmega644 MCU. Why does PORTD |= 0b00100000 work, but not PORTD |= (PD5 <<1)?


I have been trying to understand why the line

 PORTD |= 0b00100000;

works, but not

PORTD |= (PD5 <<1);

I have a LED attached to PD5 which only lights up for the first command. Do I have to define what "PD5" is? I never had to do that on my Atmega328P, but now on the Atmega644 it does not work?

Here is the libraries that I include

  #define F_CPU 1000000UL  // 1MHz internal clock
  #include <avr/io.h>
  #include <util/delay.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  #include <avr/interrupt.h>
  #include "lcd.h"

Not sure if anything can cause troubles? Am I missing something very basic here?


Solution

  • The assignments differ.

    PORTD |= 0b00100000;
    

    sets bit 5 of PORT D to 1

    whereas

    PORTD |= (PD5 <<1);
    

    set bit 1 and 2 of PORTD to 1 (as PD5 == 5 and PD5 << 1 == 10 (0x0A) i.e. 1010 binary)

    Define some macro to set the LED on or off to prevent having to set the 'bits' each time

    #define LEDON PORTD |= 0b00100000
    #define LEDOFF PORTD &= ~0b00100000
    

    Example usage

    if ( put_led_on )
        LEDON;
    else
        LEDOFF;
    

    Or thanks to your own research

    PORTD |= (1<<PD5);
    

    which will set bit 5 to 1