void digitalWrite(uint8_t pin, uint8_t val)
{
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 (val == LOW) {
*out &= ~bit;
} else {
*out |= bit;
}
SREG = oldSREG;
}
int digitalRead(uint8_t pin)
{
uint8_t timer = digitalPinToTimer(pin);
uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);
if (port == NOT_A_PIN) return LOW;
// If the pin that support PWM output, we need to turn it off
// before getting a digital reading.
if (timer != NOT_ON_TIMER) turnOffPWM(timer);
if (*portInputRegister(port) & bit) return HIGH;
return LOW;
}
I was looking at the code of these functions to see what type I should use for a wrapper function when passing HIGH and LOW, and I noticed they used different types. Since a byte obviously works to hold the value, and takes up less memory, and produces faster code, why does digitalRead return an int?
Looks to me like you have a little improvement, although maybe something drastic is planned for the Arduino Due's many pin configurations ( wild guess ), still seems like a good find to me, only little, but one none the less.
Well in the examples at least, the case could be made that using a byte might confuse beginners when they change the loop's value to something greater than 255 and don't get the result they expect.
It's one of the many quirks of the Arduino runtime environment. In my mind it's a bug, but it's not doing any great harm and I don't suppose anybody is interested in correcting it.
I can only explain that, whilst it looks strange, it is symmetric with things like Serial.read. The use of int there allows -1 to be returned to indicate "no data" and leave 0x00 through to 0xFF for "valid data".
Still, a digital pin can hardly return "no data" so maybe it just wasn't thought through fully.