user3817250
user3817250

Reputation: 1043

C - Return failure from uint8_t function

I've got a function that gets a character from a UART device when the UART buffer is non-empty.

uint8_t getByte(void) {
    while(!uartCharsAvail(uartBase)) {
        // Wait for a character to become available
    }
    return uartGetChar(uartBase);
}

The problem is now I want to introduce a timeout so that the function will return a failure if it has waited too long.

uint32_t replyTimeout;
uint8_t getByte(void) {
    replyTimeout = 0;
    while(!uartCharsAvail(uartBase)) {
        // Wait for a character to become available
        if (replyTimeout++ > MAX_REPLY_TIME) {
            return -1;
        }
        delay(1);
    }
    return uartGetChar(uartBase);
}

The problem here of course being that I'm returning a negative number from a uint8_t function.

Is there a simple way to fix this? The only way I can think to do it is to make the function boolean and pass a uint8_t pointer as a parameter.

Upvotes: 2

Views: 936

Answers (1)

chux
chux

Reputation: 153328

Just like int fgetc(), use a negative value like EOF to indicate End-of-file (the serial port no longer available) or IO Error (e.g. timeout).

With data returns, use 0 to 255 which will not collide with EOF.

The key is that getByte() needs to return 257 different things (256 different bytes and timeout). uint8_t lacks that range.

Upvotes: 2

Related Questions