robitabu:
Why should I even bother with calling assert() then?
Welcome to "Design by Contract" ... Design by contract - Wikipedia ... I highly recommend Bertrand Meyer's book.
robitabu:
Why should I even bother with calling assert() then?
Welcome to "Design by Contract" ... Design by contract - Wikipedia ... I highly recommend Bertrand Meyer's book.
robitabu:
What does actually abort() do in Arduino?
From stdlib.h:
/** The abort() function causes abnormal program termination to occur.
This realization disables interrupts and jumps to _exit() function
with argument equal to 1. In the limited AVR environment, execution is
effectively halted by entering an infinite loop. */
extern void abort(void) __ATTR_NORETURN__;
A simple error handler could be:
if (somethingBadHappens)
{
Serial.println (F("Bad thing XYZ happened."));
Serial.flush ();
exit (1);
}
The flush call will ensure the message appears before you go into the infinite loop. The F macro saves wasting valuable RAM on the message.
To ensure there is no ambiguity, I strongly agree with @PeterH...
It is never appropriate to use the AVR Libc abort.
Actually I got bitten in one of my libraries because exit() isn't always implemented. This might be neater:
if (somethingBadHappens)
{
Serial.println (F("Bad thing XYZ happened."));
Serial.flush ();
noInterrupts ();
while (true) { } // give up
}
This should get you started...
#define __ASSERT_USE_STDERR
#include <assert.h>
extern void __assert(
const char *__func,
const char *__file,
int __lineno,
const char *__sexp )
{
// Put your stuff here.
// __func is the function name (setup)
// __file is the module name (the name of your sketch)
// __lineno is the source code line number of the assert
// __sexp is the assert expression (as a C string)
Serial.print( F( "ASSERT FAILURE: " ) );
Serial.print( __file );
Serial.print( F( ": " ) );
Serial.print( __func );
Serial.print( F( ": #" ) );
Serial.print( __lineno );
Serial.println();
Serial.flush ();
noInterrupts ();
while (true) { } // give up
}
void setup( void )
{
assert( false );
}
void loop( void )
{
}
Bear in mind that each assert puts up to three string constants in SRAM. A better version would keep the string constants in Flash.
Silly me, I thought I'd need an underlying OS to abort to!
But then when I write code, I expect users to make the occasional error... since 1980.
Look on the bright side. Users expect programmers to make the occasional error, too. ![]()
Users expect programmers to make the occasional error, too.
And I never disappoint them.
From the OLD (it was old in 85) Programmer's Joke Sheet:
Users should not complain about the code they get. They are lucky to get anything at all.
1980 is when I started writing programs for engineers. Error handling became a must!
GoForSmoke:
Users should not complain about the code they get. They are lucky to get anything at all.
Priceless!!! ![]()