1

I want to set one pin's output value, and then set a different pin's output value so that the two pins change value one after the other. However, the compiler optimises the two calls to change both pins in one go.

PORTD |= _BV(0); //set pd0 to high PORTD |= _BV(1); //set pd1 to high PORTD &= ~(_BV(1)); //set pd1 to low

The two pins go high simultaneously. I tried inserting a NOP between these but it doesn't change behaviour.

(I originally intended to include an oscilloscope screengrab to show what was happening - that's how I knew (or got the wrong impression) that the two pins were changing at the same time. But the photo wasn't shifting from my Nexus 7 for me to access it from my laptop.)

7
  • I can't duplicate this behavior. Which version of GCC is in use? Dec 11 '14 at 23:49
  • What application requires those pins to be turned on one after the other, but so quickly that you don't need any code to cause a delay between the two?
    – BrettAM
    Dec 12 '14 at 0:38
  • Cool - there's an Arduino stackexchange! Thanks to the mods for migrating the question.
    – mackenir
    Dec 12 '14 at 14:58
  • It sounds like I've just got myself confused here, since the behaviour I've seen isnt repro-able.
    – mackenir
    Dec 12 '14 at 14:59
  • (by others, that is).
    – mackenir
    Dec 12 '14 at 15:26
7

I certainly can't duplicate what you are saying. The small code snippet:

void setup() {
    PORTD |= _BV(0);
    PORTD |= _BV(1);
    PORTD &= ~(_BV(1));
}

void loop() {
}

compiles into:

000000a6 <setup>:
  a6:   58 9a           sbi 0x0b, 0 ; 11
  a8:   59 9a           sbi 0x0b, 1 ; 11
  aa:   59 98           cbi 0x0b, 1 ; 11
  ac:   08 95           ret

000000ae <loop>:
  ae:   08 95           ret

That is clearly two separate bit sets followed by a bit clear.

I am using UECIDE that is set to use GCC 4.3.2

If I switch to GCC 4.8.1 instead, the code generated is identical.

Even turning on full -O3 optimization I still get the same results.

So how are you determining that it's happening at the same time?

4
  • 5
    Which makes sense since the memory location has been declared as volatile. Dec 12 '14 at 0:39
  • I think I'm using Arduino IDE 1.06 but I will need to check when I get home.
    – mackenir
    Dec 12 '14 at 15:09
  • I observed the two pins changing on an oscilloscope, but I will have to take a step back and do a test with the Arduino Micro removed from the project I'm working on. Sounds like I'm just mistaken.
    – mackenir
    Dec 12 '14 at 15:11
  • Same code generated here with avr-gcc 5.4.0. Oct 25 '19 at 14:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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