Go Down

Topic: digitalWrite writes a byte, while digitalRead returns an int. Why? (Read 615 times) previous topic - next topic

scswift

Code: [Select]

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?

pYro_65

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.

PaulS

Quote
digitalWrite writes a byte, while digitalRead returns an int. Why?

For the same reason that most examples show for loops like:
Code: [Select]
for(int i=0; i<180; i++)
{ // Move a servo }


It was code that was not subject to a lot of scrutiny/peer review.

scswift

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.

PeterH


why does digitalRead return an int?


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 only provide help via the forum - please do not contact me for private consultancy.

Nick Gammon

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.

Go Up