Skip to content

Commit f1fdffc

Browse files
committed
Add EEPROM example
1 parent 3f287f9 commit f1fdffc

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

examples/eeprom.rs

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
//! A persistent number counter.
2+
//!
3+
//! Chose random numbers in a loop until we have chosen 1000 odd numbers.
4+
//! If the device is reset it will continue, keeping track of the previous number
5+
//! of odd numbers.
6+
7+
#![no_std]
8+
#![no_main]
9+
10+
#![feature(lang_items, unwind_attributes)]
11+
12+
extern crate avr_libc;
13+
14+
use avr_libc::{eeprom_read_dword, eeprom_write_dword, random};
15+
16+
#[no_mangle]
17+
pub extern fn main() {
18+
let mut failed_attempts = load_failed_attempts();
19+
20+
while failed_attempts < 1000 {
21+
// odd numbers are bad
22+
if unsafe { random() } & 0b1 == 0b1 {
23+
failed_attempts += 1;
24+
}
25+
26+
save_failed_attempts(failed_attempts);
27+
}
28+
}
29+
30+
fn load_failed_attempts() -> u32 {
31+
unsafe {
32+
let addr = 12 as *mut u32; // chosen arbitrarily
33+
eeprom_read_dword(addr)
34+
}
35+
}
36+
37+
fn save_failed_attempts(attempts: u32) {
38+
unsafe {
39+
let addr = 12 as *mut u32; // chosen arbitrarily
40+
eeprom_write_dword(addr, attempts);
41+
}
42+
}
43+
44+
// These do not need to be in a module, but we group them here for clarity.
45+
pub mod std {
46+
#[lang = "eh_personality"]
47+
#[no_mangle]
48+
pub unsafe extern "C" fn rust_eh_personality(_state: (), _exception_object: *mut (), _context: *mut ()) -> () {
49+
}
50+
51+
#[lang = "panic_fmt"]
52+
#[unwind]
53+
pub extern fn rust_begin_panic(_msg: (), _file: &'static str, _line: u32) -> ! {
54+
loop { }
55+
}
56+
}
57+

0 commit comments

Comments
 (0)