Skip to content

Commit 3c02df9

Browse files
authored
examples: nano: Add panic example
1 parent 9433af7 commit 3c02df9

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

examples/arduino-nano/Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,6 @@ embedded-hal = "0.2.3"
1414
[dependencies.arduino-hal]
1515
path = "../../arduino-hal/"
1616
features = ["arduino-nano"]
17+
18+
[dependencies.avr-device]
19+
version = "0.5.1"
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*!
2+
* Example of a custom panic handler.
3+
*
4+
* The panic handler will print out where the panic occurred and then blink the oboard LED rapidly
5+
* to make the user aware of the problem.
6+
*/
7+
#![no_std]
8+
#![no_main]
9+
10+
use arduino_hal::prelude::*;
11+
12+
// Documentation build does not like this and fails with the following error, even though
13+
// everything is fine when compiling the binary.
14+
//
15+
// error[E0152]: found duplicate lang item `panic_impl`
16+
//
17+
// Ignore the panic handler in documentation builds. This is not needed in downstream code, it is
18+
// an artifact of the avr-hal examples structure.
19+
#[cfg(not(doc))]
20+
#[panic_handler]
21+
fn panic(info: &core::panic::PanicInfo) -> ! {
22+
// disable interrupts - firmware has panicked so no ISRs should continue running
23+
avr_device::interrupt::disable();
24+
25+
// get the peripherals so we can access serial and the LED.
26+
//
27+
// SAFETY: Because main() already has references to the peripherals this is an unsafe
28+
// operation - but because no other code can run after the panic handler was called,
29+
// we know it is okay.
30+
let dp = unsafe { arduino_hal::Peripherals::steal() };
31+
let pins = arduino_hal::pins!(dp);
32+
let mut serial = arduino_hal::default_serial!(dp, pins, 57600);
33+
34+
// Print out panic location
35+
ufmt::uwriteln!(&mut serial, "Firmware panic!\r").void_unwrap();
36+
if let Some(loc) = info.location() {
37+
ufmt::uwriteln!(
38+
&mut serial,
39+
" At {}:{}:{}\r",
40+
loc.file(),
41+
loc.line(),
42+
loc.column(),
43+
)
44+
.void_unwrap();
45+
}
46+
47+
// Blink LED rapidly
48+
let mut led = pins.d13.into_output();
49+
loop {
50+
led.toggle();
51+
arduino_hal::delay_ms(100);
52+
}
53+
}
54+
55+
#[arduino_hal::entry]
56+
fn main() -> ! {
57+
let dp = arduino_hal::Peripherals::take().unwrap();
58+
let pins = arduino_hal::pins!(dp);
59+
let mut serial = arduino_hal::default_serial!(dp, pins, 57600);
60+
61+
ufmt::uwriteln!(&mut serial, "Hello from Arduino!\r").void_unwrap();
62+
ufmt::uwriteln!(&mut serial, "Panic in 5 seconds!\r").void_unwrap();
63+
64+
arduino_hal::delay_ms(5000);
65+
66+
// Panic messages cannot yet be captured because they rely on core::fmt
67+
// which is way too big for AVR
68+
panic!();
69+
}

0 commit comments

Comments
 (0)