Is it possible to use port labels like PD0, PC3, PB2 to address pins using digitalWrite()?

Good day, everyone.

I'm currently defining some macros for pins for a standalone Atmega328 project board. I have made a mistake of incorrectly corelating pins labelled as PB3 with a digital pin in Arduino IDE a few times. This got me thinking, is it possible to just use PB2, PC2 etc to directly address those pins? Or perhaps is there a definitions file already available out there, that I can include in the sketch that would allow me to use port and pin names directly as I see them on the symbol of the atmega328 in kiCad?

Not sure what you exactly want.

Perhaps you should Google Arduino direct port manipulation.

It's not really direct port manupulation.
You see, Schematic symbols don't list pins as Digital 1, Amalog 3. They list them as PD1, PB2.

Is there a way to then do
digitalWrite(PB3, LOW) for example? instead of digitalWrite(7, LOW) ? Currently I can only achieve this with Macros

You can use the define preprocessor directive, like this:

#define PB0 D8

void setup() {
  pinMode(PB0, OUTPUT);
}

I see. so I have to create these myself to be able to do this.
Well alrighty. Thanks.

If you did so, the code would not be portable between different Arduinos, and error prone when editing in the case that the project wiring changes.

Try this and see if it does what you want:

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
Serial.println(PB3);
digitalWrite(PB3, LOW);
}

void loop() {
  // put your main code here, to run repeatedly:

}

I think you have to. But it's a rather small task that you only have to do once.

1 Like

All these PAx, PBx, PDx, etc. are values from 0 to 7 and only specify a bit in a register,
but not the register in which the bit resides.

No, not in general, because the predefined PB6 is the same value as the predefined PD6 (and etc.)

There is a convention followed in some "cores" to define PIN_Pxx values that map the pin names to their Arduino pin numbers (perhaps "many" cores? All of Spence Konde's and the Hans "MCUDude" cores seem to do it.)

For example, from MegaCore's "100pin Arduino Mega" variant:

#define PIN_PE0 0
#define PIN_PE1 1
#define PIN_PE4 2
#define PIN_PE5 3
#define PIN_PG5 4
#define PIN_PE3 5
#define PIN_PH3 6
#define PIN_PH4 7
  : etc

On the Arduino UNO and Nano it works... but only for PD0 through PD7 (which happen to be Pin 0 through Pin 7).

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.