Skip to content

Instantly share code, notes, and snippets.

@bplaat
Created February 2, 2023 12:19
Show Gist options
  • Save bplaat/42a23985846579efadd4fa2243d68a7c to your computer and use it in GitHub Desktop.
Save bplaat/42a23985846579efadd4fa2243d68a7c to your computer and use it in GitHub Desktop.
A simple rust blink program for Arduino Uno
{
"arch": "avr",
"cpu": "atmega328p",
"data-layout": "e-P1-p:16:8-i8:8-i16:8-i32:8-i64:8-f32:8-f64:8-n8-a:8",
"env": "",
"executables": true,
"linker": "avr-gcc",
"linker-flavor": "gcc",
"linker-is-gnu": true,
"llvm-target": "avr-unknown-unknown",
"os": "unknown",
"position-independent-executables": false,
"exe-suffix": ".elf",
"eh-frame-header": false,
"pre-link-args": {
"gcc": ["-mmcu=atmega328p"]
},
"late-link-args": {
"gcc": ["-lgcc"]
},
"target-c-int-width": "16",
"target-endian": "little",
"target-pointer-width": "16",
"vendor": "unknown"
}
cargo build -Z build-std=core --target avr-atmega328p.json --release || exit
avr-objcopy -O ihex -R .eeprom target/avr-atmega328p/release/blink.elf target/avr-atmega328p/release/blink.hex
avrdude -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:w:target/avr-atmega328p/release/blink.hex:i
[package]
name = "blink"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[profile.dev]
panic = "abort"
[profile.release]
panic = "abort"
[dependencies]
#![no_std]
#![no_main]
#![feature(asm_experimental_arch)]
use core::arch::asm;
use core::panic::PanicInfo;
// Ports
const DDRB: *mut u8 = 0x24 as *mut u8;
const PORTB: *mut u8 = 0x25 as *mut u8;
// Delay
fn delay(ms: u32) {
for _ in 0..(ms / 16) {
let count = 0xffff as u16;
unsafe {
asm!("1: sbiw {i}, 1",
"brne 1b",
i = inout(reg_iw) count => _,
)
}
}
}
// Main
#[no_mangle]
pub extern "C" fn main() {
// Set build in led to output
unsafe {
core::ptr::write_volatile(DDRB, core::ptr::read_volatile(DDRB) | 0b00100000);
}
loop {
// On
unsafe {
core::ptr::write_volatile(PORTB, core::ptr::read_volatile(PORTB) | 0b00100000);
}
delay(500);
// Off
unsafe {
core::ptr::write_volatile(PORTB, core::ptr::read_volatile(PORTB) & (!0b00100000));
}
delay(500);
}
}
// Panic handler
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment