I am using a custom Arduino Nano compatible board with an Atmel 328P. I am externally changing the values applied to several pins on PORTB. I expect to be able to read the values of these pins (low or high) but I always read zeroes. However, the pin change interrupt is called. What do I need to do to read values from PORTB?

Supply voltage is 5 volts. Pin applied high voltage is 3.3 volts.

With the below code, when I change the voltage applied to a pin, LED1 flashes but LED2 does not.

#include <avr/interrupt.h>

#define LED1_PORT                           (PORTD)
#define LED1_PIN_bm                         (_BV(4))         //D1, white

#define LED2_PORT                           (PORTD)
#define LED2_PIN_bm                         (_BV(3))         //D2, red

volatile bool g_bValueChanged = 0;

void setup()
  DDRB = 0;                     //set all as inputs
  PCMSK0 = 0xfb;                //exclude 1 pin because of noise
  PCICR |= (1 << PCIE0);        //enable pin change interrupt 0 (for pins PB0..7)


uint8_t g_valuePrevious = 0;

void loop()
  if (g_bValueChanged)
    g_bValueChanged = false;

    LED1_PORT |= LED1_PIN_bm;
    LED1_PORT &= ~LED1_PIN_bm;

  uint8_t value = PORTB;
  if (value != g_valuePrevious)
    g_valuePrevious = value;
    LED2_PORT |= LED2_PIN_bm;
    LED2_PORT &= ~LED2_PIN_bm;

    g_bValueChanged = true;

1 Answer 1


The PORTB register is initialized by the hardware to zero. You never write to this register, so it always stays zero.

Maybe you are mixing up PORTB and PINB:

  • PORTB is the port output register, controlled by you
  • PINB is the port input register, for which the bits corresponding to input pins are controlled by whatever drives those pins from the outside.
  • I am applying a signal to those pins externally. I have been programming XMega which uses the same PORTB for input and output. Now I see PINB in the datasheet, you are probably correct, I will try it.
    – Joe
    Jul 9, 2022 at 18:54
  • @Joe: Yes, that is what I understood from reading your question. Jul 9, 2022 at 18:55
  • Thank you, that was the answer, I was not aware that the processor I am using had different registers for input and output.
    – Joe
    Jul 10, 2022 at 15:13
  • Different registers, indeed. And there is even a free goodie: if you attempt to write to the port input registers, you get toggle functionality: for every bit you write to one, the corresponding output pin is toggled. Jul 10, 2022 at 16:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.