Most memory efficient way to set a port bit to the value of another bit

I'm trying to find a more memory efficient way to read one bit from a port and write it to another. The best I can find so far is below, but it takes 456B of memory. Any suggestions to make this more memory efficient?

void setup() {
  DDRD = DDRD | B00000100;

void loop() {
  bitWrite(PORTD, 2, bitRead(PIND, 3));


This program takes 450 bytes, just the Arduino minimum, so your code only takes 12 bytes.

void setup()


void loop()

Sketch uses 462 bytes (1%) of program storage space. Maximum is 30,720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.


Note that:

bitWrite(PORTD, 2, bitRead(PIND, 3));

is not interrupt-safe. It does a read-modify-write on PORTD. That operation is non-atomic. So, if an interrupt occurs between the read and the write and that ISR modifies PORTD, then your code will corrupt that modification.

Your code should be in a critical section.

Thanks! No interrupts to worry about with this project.

Thanks! No interrupts to worry about with this project.

That you know of .....
It costs next to nothing to put that code in a critical section.

Even if an interrupt did occur and even if it happened between the read and write it would not affect the overall outcome for this project.

Have it your way since you think you know what’s going on.

What's your problem? I asked a question about making code more efficient and JCA34F answered it for me. You don't even know what this project is. Tell me, genius, how an interrupt is going to be a problem for this project that you know nothing about? Or shut your mouth and go bother someone else.

Hey robonick, please keep it civil.

There are interrupts going on, all the time, unless you have disabled them. micros() and millis() use interrupts for time keeping as one example, about every 4uS.


I know how microcontrollers and microprocessors work. I've been programming them since the early 80's. I know all about interrupts. They will have no effect on this project. There is no reason for this gfvalvo to take this off topic with his ideas about what this project involves. It was a simple question about making one specific piece of code out of over a hundred lines more efficient. I thanked him for his advice and told him that the interrupts would not be relevant with this project. There was no need for him to continue on with his insulting comments. You should be telling him to keep it civil. Unless this forum is all about know it all's talking down to people.