Go Down

Topic: suggestion to add TOGGLE in digitalWrite() (Read 5 times) previous topic - next topic

sv1eed

hello,
i didn't do much of a research about it (not much free time), but i think the library does not provide an easy/efficient way to toggle a pin.

anyway, i modified wiring.h and added:
...
#define HIGH 0x1
#define LOW  0x0
#define TOGGLE  0x2   // added line
...

and wiring_digital.c and changed to:
     if (val == LOW) *out &= ~bit;
     if (val == HIGH) *out |= bit; // added line
     if (val == TOGGLE) *out ^= bit; // added line
     // replaced line // else *out |= bit;


now it looks like i can write for example:
digitalWrite(ledPin, TOGGLE);
instead of calling other functions or keeping the state of the pin in the program.

if this modification does not create any issues, i think it would be a nice addition to a next version.

- chris

Osgeld

#1
Aug 18, 2010, 10:45 pm Last Edit: Aug 18, 2010, 10:48 pm by Osgeld Reason: 1
what speed does it toggle at? (and what if I want it faster or slower)

;)

and it already keeps the state of the pin that is why

pin = !pin works
[edit]
oh nevermind, i just re-read that, yea I guess that could be more noob friendly than the above, so why not [/edit]

westfw

Quote
so why not

Well, changing the "any non-zero value causes a 1 to be written" behavior may screw up any number of existing sketches...

BenF

Quote
Well, changing the "any non-zero value causes a 1 to be written" behavior may screw up any number of existing sketches...

I agree to this - it really is not wise to change this behavior considering backwards compatibility.

That AVR's support a lesser known direct pin toggle, so for those who don't mind using direct port IO, you can do toggle as follows:

Code: [Select]

// Example is for digital pin 2.

PIND = _BV(PIND2);  // toggle pin2 on AtMega168/328


deSilva

#4
Aug 19, 2010, 03:10 pm Last Edit: Aug 19, 2010, 03:10 pm by mpeuser Reason: 1
There seems to be a problem with the forum's software
The code should read
Code: [Select]
PIND ^= _BV(PIND2)

Go Up