Skip to content

Adding a toggle function to wiring_digital.c #11777

Closed
@Perehama

Description

@Perehama

I suggest the code below be added to wiring_digital.c and the Arduino language. This would make the task easier for beginning programmers and eliminate the need to check the state of the pin first, making a speed improvement at the same time.

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 (timer != NOT_ON_TIMER) turnOffPWM(timer);
  out = portOutputRegister(port);
  uint8_t oldSREG = SREG;
  cli();
  *out ^= bit;
  SREG = oldSREG;
}

Activity

matthijskooijman

matthijskooijman commented on Mar 31, 2022

@matthijskooijman
Collaborator

Thanks for you suggestion. I edited your post to use triple backticks to create a more readable code block.

Also, change to the Arduino API like this should be coordinated between cores, this coordination of happens in the ArduinoCore-API repository. There is already an issue about this, see arduino/ArduinoCore-API#130, so I'm going to close this issue and direct you to that one (feel free to add more info and new arguments to it, but if you just want to voice support for it, please use a thumbsup rather than a "me too" comment).

Also, note that on AVR, toggling can be implemented even faster by writing to the input register, which makes the hardware toggle pins.

added
Component: CoreRelated to the code for the standard Arduino API
feature requestA request to make an enhancement (not a bug fix)
Type: DuplicateAnother item already exists for this topic
on Mar 31, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Component: CoreRelated to the code for the standard Arduino APIType: DuplicateAnother item already exists for this topicfeature requestA request to make an enhancement (not a bug fix)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @matthijskooijman@per1234@Perehama

        Issue actions

          Adding a toggle function to wiring_digital.c · Issue #11777 · arduino/Arduino