How to display an Error message?

Go To Last Post
7 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I'm creating a function of void type that just sets a pin deppending on the pin number you enter to the argument on a microcontroller, and I want to show an error message if the pin number that you enter in the argument is larger than 7 (that's why I made the function, just to try and test showing the error message), but I can't make it work... how would the syntax for it be?

 

this is what I tried...

void setBit(char bit)
{
    //Here I want to put the error routine
    if(bit > 7)
    {
        #error "Bit must be less than 7" //This is not working for me...
    }
    
    PORTB |= (1<<bit);
}

 

Victor

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

#error is a compile time operator. You seem to want a run time function. Where would you report the error?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I want it to appear when I try to compile the code, so an error would appear when pressing build / compile the code... like when you miss an ";"

Victor

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The bit value is unknown at compile time. You would need to detect the error where the bit value passed to that function is defined.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Make the function non-void, and return an error code. Typically 0x00 -> no error and other values represent the various possible errors.

 

Jim

 

Jim Wagner Oregon Research Electronics, Consulting Div. Tangent, OR, USA http://www.orelectronics.net

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

C library functions have errno; could do similar for the application's functions.

https://www.nongnu.org/avr-libc/user-manual/group__avr__errno.html

 

"Dare to be naïve." - Buckminster Fuller

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Ahh.  This is where you discover that C's macro language really sucks, compared to "real" macro and "compile-time" capabilities that you may be used to from assembly language.

You can cheat:

 

static inline void setBit(const char bit)
{
    asm volatile(" .if %0 > 7\n\t"
		 "  .print \"Bit must be less than 7\"\n\t"
		 "  .err \n\t"
		 " .endif \n\t"::"I"(bit));
   
    PORTB |= (1<<bit);
}

int main() {
    setBit(5);
    setBit(10);
}

 

(Note that this won't generate very good error messages, since it happens at assemble-time, well after compilation is done.  There might be tricky ways to pass the line number and filename to the assembler...)

 

There's probably a way to do this with C++ templates, too.