digitalToggle(uint8_t pin)

76 views
Skip to first unread message

Daniel De Kock

unread,
Apr 16, 2014, 8:23:18 AM4/16/14
to devel...@arduino.cc
i Know there is a library called "digitalToggle" that enables one to toggle a pin, But I found it easier to add the function to my Wiring_digital.c and Arduino.h in the core
I copied digitalWrite and changed a line to get a toggle method:

void digitalToggle(uint8_t pin)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    volatile uint8_t *out;

    if (port == NOT_A_PIN) return;

    // If the pin that support PWM output, we need to turn it off
    // before doing a digital write.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    out = portOutputRegister(port);

    uint8_t oldSREG = SREG;
    cli();
   
    if(*out & bit){ // This is all that is different from digitalWrite
    *out &= ~bit;
    }
    else{
    *out |= bit;
    }
   
    SREG = oldSREG;
}


I have been using toggling a lot to make heartbeat LEDs or to reverse motor directions etc.

it might be useful to others.

I only discovered "http://playground.arduino.cc/Code/DigitalToggle" afterwards :(

Rob Tillaart

unread,
Apr 16, 2014, 12:46:46 PM4/16/14
to Arduino Developers
    [code]
    if(*out & bit){ // This is all that is different from digitalWrite
    *out &= ~bit; 
    }
    else{ 
    *out |= bit;
    }[/code]

==>

*out ^= bit;   ??




--
You received this message because you are subscribed to the Google Groups "Developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to developers+...@arduino.cc.

Daniel de Kock

unread,
Apr 16, 2014, 2:56:01 PM4/16/14
to devel...@arduino.cc


XOR bit toggle will work too :)
( should be faster and lower code footprint too )
You received this message because you are subscribed to a topic in the Google Groups "Developers" group.
To unsubscribe from this topic, visit https://groups.google.com/a/arduino.cc/d/topic/developers/iPl3bECVISM/unsubscribe.
To unsubscribe from this group and all its topics, send an email to developers+...@arduino.cc.

Mikael Patel

unread,
Apr 16, 2014, 3:39:06 PM4/16/14
to devel...@arduino.cc
Reply all
Reply to author
Forward
0 new messages