Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to use assertions with Arduino.
#define __ASSERT_USE_STDERR
#include <assert.h>
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
// initialize serial communication at 9600 bits per second.
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
for (uint8_t i = 0; i < 3; i++) {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
// make assertion failed.
assert(false);
}
// handle diagnostic informations given by assertion and abort program execution:
void __assert(const char *__func, const char *__file, int __lineno, const char *__sexp) {
// transmit diagnostic informations through serial link.
Serial.println(__func);
Serial.println(__file);
Serial.println(__lineno, DEC);
Serial.println(__sexp);
Serial.flush();
// abort program execution.
abort();
}
@zacsketches

This comment has been minimized.

Copy link

@zacsketches zacsketches commented Mar 21, 2016

Thanks for documenting this. I was able to put it to use today.
Plus 1 star!

@gundamlh

This comment has been minimized.

Copy link

@gundamlh gundamlh commented Sep 10, 2016

Many thanks for sharing! It works!

@Pigeo

This comment has been minimized.

Copy link

@Pigeo Pigeo commented Jan 28, 2017

Unfortunately, it doesn't work on Arduino DUE :
__assert() function isn't called and I get the standard error message instead :

assertion "false" failed: file "/assert.ino", line 31, function: void loop()
Exiting with status 1.

Do you have any idea why it doesn't work on Arduino DUE ?
(However I successfully tested it on Arduino MEGA by the way)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment