digitalWrite (in)compatibility with Arduino?

I’m not sure if this is only a misinterpretation on my part or if there realy is an “incompatibility” in the inner workings of digitalWrite() on the Core.

I’ve never worked with a vanilla Arduino, but used Teensyduino and got the impression that it is as close as it can get to pure Arduino and so I just did what I’m used to on the Core and got a bit puzzled.

The Arduino/Teensyduino does blink the on-board LED when I do this

int iLED = 0;
...
loop()
{
  iLED ^= -1;  // easy XOR toggle iLED 0x00000000 -> 0xFFFFFFFF -> 0x00000000 -> ...
  digitalWrite(LED_PIN, iLED);    // any iLED != 0 is considered HIGH
  // or shorter digitalWrite(LED_PIN, iLED ^= 1);
  deleay(1000);
}

but the Core does not, unless I do something like this

  digitalWrite(LED_PIN, iLED ? HIGH : LOW);

Is it intended (and wise) to restrict the meaning of HIGH to only “1” - thus possibly breaking some Arduino sketches that use “mathematical” approaches (e. g. digitalWrite(LED_PIN, ++i % 5); for a HIGH:LOW ratio of 4:1) and rely on “anything but 0x0” to be HIGH, just like C if-statements consider anything but ‘0x0’ as TRUE?
Sure it can be done with a ternary if as above or any other way of translation, but for what?

Where :spark: Core’s implementation of digitalWrite() does this

if (value == HIGH)
{
	PIN_MAP[pin].gpio_peripheral->BSRR = PIN_MAP[pin].gpio_pin;
}
else if (value == LOW)
{
	PIN_MAP[pin].gpio_peripheral->BRR = PIN_MAP[pin].gpio_pin;
}

Arduino’s implementation does that:

if (val == LOW) {
	*out &= ~bit;
} else {
	*out |= bit;
}

When value is an uint8_t I’d expect that any uint8_t might do something - as is the case in the latter version - but the Core’s implementation only does something actively for the values 0 and 1 and nothing for all the other 254 possible values.

Good call @ScruffR

Seems pretty clear to me that it should just be changed to:

if (value == LOW)
{
	PIN_MAP[pin].gpio_peripheral->BRR = PIN_MAP[pin].gpio_pin;
}
else
{
	PIN_MAP[pin].gpio_peripheral->BSRR = PIN_MAP[pin].gpio_pin;
}
2 Likes

Should be an easy fix - not calling for aPullRequest :wink:

Oh I’m glad you’re offering though :wink: Thanks!