Merge branch 'embedded_hal_1_0' into 'main'

Changed to rp2040hal v0.11 and embedded_hal v1.0

See merge request cm/cmdr-joystick!2
This commit is contained in:
Christoffer Martinsson 2025-03-09 15:48:14 +01:00
commit 6199c80a0a
6 changed files with 128 additions and 123 deletions

View File

@ -1,13 +1,9 @@
#
# Cargo Configuration for the https://github.com/rp-rs/rp-hal.git repository.
#
# Copyright (c) The RP-RS Developers, 2021
#
# You might want to make a similar file in your own repository if you are
# writing programs for Raspberry Silicon microcontrollers.
#
# This file is MIT or Apache-2.0 as per the repository README.md file
#
[build]
# Set the default target to match the Cortex-M0+ in the RP2040
@ -23,13 +19,12 @@ target = "thumbv6m-none-eabi"
# script. This is usually provided by the cortex-m-rt crate, and by default
# the version in that crate will include a file called `memory.x` which
# describes the particular memory layout for your specific chip.
# * inline-threshold=5 makes the compiler more aggressive and inlining functions
# * no-vectorize-loops turns off the loop vectorizer (seeing as the M0+ doesn't
# have SIMD)
rustflags = [
"-C", "link-arg=--nmagic",
"-C", "link-arg=-Tlink.x",
"-C", "inline-threshold=5",
"-C", "link-arg=-Tdefmt.x",
"-C", "no-vectorize-loops",
]
@ -39,4 +34,4 @@ runner = "elf2uf2-rs -d"
# This runner will find a supported SWD debug probe and flash your RP2040 over
# SWD:
# runner = "probe-run --chip RP2040"
# runner = "probe-rs run --chip RP2040"

View File

@ -1,58 +1,68 @@
[package]
name = "rp2040"
version = "0.1.0"
edition = "2021"
version = "0.2.0"
edition = "2024"
[dependencies]
# rp2040_hal dependencies copied from v0.11
cortex-m = "0.7.2"
waveshare-rp2040-zero = "0.6.0"
rp2040-boot2 = { version = "0.2.0", optional = true }
rp2040-hal = { version = "0.8.0" }
cortex-m-rt = { version = "0.7", optional = true }
panic-halt= "0.2.0"
embedded-hal ="0.2.5"
log = { version = "0.4", optional = true }
fugit = "0.3.5"
nb = "1.0.0"
smart-leds = "0.3.0"
smart-leds-trait = "0.2.1"
ws2812-pio = "0.6.0"
usbd-human-interface-device = "0.4.2"
usb-device = "0.2"
cortex-m-rt = "0.7"
cortex-m-rtic = "1.1.4"
critical-section = {version = "1.2.0"}
defmt = {version = "0.3", optional=true}
defmt-rtt = "0.4.0"
dht-sensor = "0.2.1"
embedded-alloc = "0.5.1"
embedded-hal = "1.0.0"
embedded-hal-async = "1.0.0"
embedded-hal-bus = {version = "0.2.0", features = ["defmt-03"]}
embedded-io = "0.6.1"
embedded_hal_0_2 = {package = "embedded-hal", version = "0.2.5", features = ["unproven"]}
fugit = "0.3.6"
futures = {version = "0.3.30", default-features = false, features = ["async-await"]}
hd44780-driver = "0.4.0"
nb = "1.0"
panic-halt = "0.2.0"
panic-probe = {version = "0.3.1", features = ["print-defmt"]}
pio = "0.2.0"
defmt = { version = "0.3", optional = true }
libm = "0.2.7"
pio-proc = "0.2.0"
portable-atomic = {version = "1.7.0", features = ["critical-section"]}
rp2040-boot2 = "0.3.0"
rp2040-hal = {version = "0.11.0", features = ["binary-info", "critical-section-impl", "rt", "defmt"]}
static_cell = "2.1.0"
# USB hid dependencies
#usbd-human-interface-device = {version = "0.5.1", features = ["defmt"]}
usbd-human-interface-device = {version = "0.5.1"}
usb-device = "0.3"
packed_struct = { version = "0.10", default-features = false }
heapless = "0.8"
# Other dependencies
eeprom24x = "0.7.2"
ws2812-pio = "0.9.0"
dyn-smooth = "0.2.0"
eeprom24x = "0.6.0"
libm = "0.2.7"
smart-leds = "0.4.0"
[features]
# This is the set of features we enable by default
default = ["boot2", "rt", "critical-section-impl", "rom-func-cache"]
# critical section that is safe for multicore use
critical-section-impl = ["rp2040-hal/critical-section-impl"]
# 2nd stage bootloaders for rp2040
boot2 = ["rp2040-boot2"]
# Minimal startup / runtime for Cortex-M microcontrollers
rt = ["cortex-m-rt","rp2040-hal/rt"]
# This enables a fix for USB errata 5: USB device fails to exit RESET state on busy USB bus.
# Only required for RP2040 B0 and RP2040 B1, but it doesn't hurt to enable it
rp2040-e5 = ["rp2040-hal/rp2040-e5"]
# Memoize(cache) ROM function pointers on first use to improve performance
rom-func-cache = ["rp2040-hal/rom-func-cache"]
# Disable automatic mapping of language features (like floating point math) to ROM functions
disable-intrinsics = ["rp2040-hal/disable-intrinsics"]
# This enables ROM functions for f64 math that were not present in the earliest RP2040s
rom-v2-intrinsics = ["rp2040-hal/rom-v2-intrinsics"]
defmt = ["dep:defmt", "usb-device/defmt"]
# [target.'cfg( target_arch = "arm" )'.dependencies]
# embassy-executor = {version = "0.5", features = ["arch-cortex-m", "executor-thread"]}
[lints.clippy]
too_long_first_doc_paragraph = "allow"
[profile.release]
codegen-units = 1
debug = 2
debug-assertions = false
incremental = false
lto = 'fat'
opt-level = 3
overflow-checks = false
[[bin]]
name = "rp2040"
test = false

View File

@ -6,7 +6,7 @@
use core::convert::Infallible;
use cortex_m::delay::Delay;
use embedded_hal::digital::v2::*;
use embedded_hal::digital::{InputPin, OutputPin};
/// Button matrix driver
///
@ -15,7 +15,7 @@ use embedded_hal::digital::v2::*;
/// let button_matrix: ButtonMatrix<4, 6, 48> = ButtonMatrix::new(row_pins, col_pins, 5);
/// ```
pub struct ButtonMatrix<'a, const R: usize, const C: usize, const N: usize> {
rows: &'a [&'a dyn InputPin<Error = Infallible>; R],
rows: &'a mut [&'a mut dyn InputPin<Error = Infallible>; R],
cols: &'a mut [&'a mut dyn OutputPin<Error = Infallible>; C],
pressed: [bool; N],
debounce: u8,
@ -31,7 +31,7 @@ impl<'a, const R: usize, const C: usize, const N: usize> ButtonMatrix<'a, R, C,
/// * `cols` - An array of references to the column pins.
/// * `debounce` - The debounce time in number of scans.
pub fn new(
rows: &'a [&'a dyn InputPin<Error = Infallible>; R],
rows: &'a mut [&'a mut dyn InputPin<Error = Infallible>; R],
cols: &'a mut [&'a mut dyn OutputPin<Error = Infallible>; C],
debounce: u8,
) -> Self {

View File

@ -72,35 +72,38 @@ use core::convert::Infallible;
use cortex_m::delay::Delay;
use dyn_smooth::{DynamicSmootherEcoI32, I32_FRAC_BITS};
use eeprom24x::{Eeprom24x, SlaveAddr};
use embedded_hal::adc::OneShot;
use embedded_hal::digital::v2::*;
use embedded_hal::timer::CountDown;
use embedded_hal::digital::{InputPin, OutputPin};
use embedded_hal_0_2::adc::OneShot;
use embedded_hal_0_2::timer::CountDown;
use fugit::{ExtU32, RateExtU32};
use libm::powf;
use panic_halt as _;
use rp2040_hal::{
Sio,
adc::Adc,
gpio::{Function, FunctionConfig, PinId, ValidPinMode},
adc::AdcPin,
clocks::{Clock, init_clocks_and_plls},
gpio::{AnyPin, Pins},
i2c::I2C,
pio::StateMachineIndex,
pac,
pio::{PIOExt, StateMachineIndex},
timer::Timer,
watchdog::Watchdog,
};
use status_led::{StatusMode, Ws2812StatusLed};
use usb_device::class_prelude::*;
use usb_device::prelude::*;
use usb_joystick_device::{JoystickConfig, JoystickReport};
use usbd_human_interface_device::prelude::*;
use waveshare_rp2040_zero::entry;
use waveshare_rp2040_zero::{
hal::{
clocks::{init_clocks_and_plls, Clock},
pac,
pio::PIOExt,
timer::Timer,
watchdog::Watchdog,
Sio,
},
Pins, XOSC_CRYSTAL_FREQ,
};
// The linker will place this boot block at the start of our program image. We
/// need this to help the ROM bootloader get our code up and running.
#[unsafe(link_section = ".boot2")]
#[unsafe(no_mangle)]
#[used]
pub static BOOT2_FIRMWARE: [u8; 256] = rp2040_boot2::BOOT_LOADER_W25Q080;
const XTAL_FREQ_HZ: u32 = 12_000_000u32;
// Public constants
pub const BUTTON_ROWS: usize = 5;
@ -177,7 +180,7 @@ impl Default for GimbalAxis {
}
}
#[entry]
#[rp2040_hal::entry]
fn main() -> ! {
// Grab our singleton objects
let mut pac = pac::Peripherals::take().unwrap();
@ -187,7 +190,7 @@ fn main() -> ! {
// Configure clocks and PLLs
let clocks = init_clocks_and_plls(
XOSC_CRYSTAL_FREQ,
XTAL_FREQ_HZ,
pac.XOSC,
pac.CLOCKS,
pac.PLL_SYS,
@ -213,8 +216,8 @@ fn main() -> ! {
let i2c = I2C::i2c1(
pac.I2C1,
pins.gp14.into_mode(), // sda
pins.gp15.into_mode(), // scl
pins.gpio14.reconfigure(), // sda
pins.gpio15.reconfigure(), // scl
400.kHz(),
&mut pac.RESETS,
125_000_000.Hz(),
@ -229,27 +232,27 @@ fn main() -> ! {
// Configure ADC input pins
// Have not figured out hov to store the adc pins in an array yet
// TODO: Find a way to store adc pins in an array
let mut adc_pin_left_x = pins.gp29.into_floating_input();
let mut adc_pin_left_y = pins.gp28.into_floating_input();
let mut adc_pin_right_x = pins.gp27.into_floating_input();
let mut adc_pin_right_y = pins.gp26.into_floating_input();
let mut adc_pin_left_x = AdcPin::new(pins.gpio29.into_floating_input()).unwrap();
let mut adc_pin_left_y = AdcPin::new(pins.gpio28.into_floating_input()).unwrap();
let mut adc_pin_right_x = AdcPin::new(pins.gpio27.into_floating_input()).unwrap();
let mut adc_pin_right_y = AdcPin::new(pins.gpio26.into_floating_input()).unwrap();
// Setting up array with pins connected to button rows
let button_matrix_row_pins: &[&dyn InputPin<Error = Infallible>; BUTTON_ROWS] = &[
&pins.gp6.into_pull_up_input(),
&pins.gp8.into_pull_up_input(),
&pins.gp4.into_pull_up_input(),
&pins.gp7.into_pull_up_input(),
&pins.gp5.into_pull_up_input(),
let button_matrix_row_pins: &mut [&mut dyn InputPin<Error = Infallible>; BUTTON_ROWS] = &mut [
&mut pins.gpio6.into_pull_up_input(),
&mut pins.gpio8.into_pull_up_input(),
&mut pins.gpio4.into_pull_up_input(),
&mut pins.gpio7.into_pull_up_input(),
&mut pins.gpio5.into_pull_up_input(),
];
// Setting up array with pins connected to button columns
let button_matrix_col_pins: &mut [&mut dyn OutputPin<Error = Infallible>; BUTTON_COLS] = &mut [
&mut pins.gp9.into_push_pull_output(),
&mut pins.gp10.into_push_pull_output(),
&mut pins.gp11.into_push_pull_output(),
&mut pins.gp12.into_push_pull_output(),
&mut pins.gp13.into_push_pull_output(),
&mut pins.gpio9.into_push_pull_output(),
&mut pins.gpio10.into_push_pull_output(),
&mut pins.gpio11.into_push_pull_output(),
&mut pins.gpio12.into_push_pull_output(),
&mut pins.gpio13.into_push_pull_output(),
];
// Create button matrix object that scans all buttons
@ -260,13 +263,13 @@ fn main() -> ! {
button_matrix.init_pins();
// Setup extra buttons (connected to TX/RX pins)
let left_extra_button = pins.gp1.into_pull_up_input();
let right_extra_button = pins.gp0.into_pull_up_input();
let mut left_extra_button = pins.gpio1.into_pull_up_input();
let mut right_extra_button = pins.gpio0.into_pull_up_input();
// Create status LED
let (mut pio, sm0, _, _, _) = pac.PIO0.split(&mut pac.RESETS);
let mut status_led = Ws2812StatusLed::new(
pins.neopixel.into_mode(),
pins.gpio16.into_function(),
&mut pio,
sm0,
clocks.peripheral_clock.freq(),
@ -290,7 +293,7 @@ fn main() -> ! {
}
// Create timers
let timer = Timer::new(pac.TIMER, &mut pac.RESETS);
let timer = Timer::new(pac.TIMER, &mut pac.RESETS, &clocks);
let mut status_led_count_down = timer.count_down();
status_led_count_down.start(250.millis());
@ -393,7 +396,7 @@ fn main() -> ! {
];
// Configure USB
let usb_bus = UsbBusAllocator::new(waveshare_rp2040_zero::hal::usb::UsbBus::new(
let usb_bus = UsbBusAllocator::new(rp2040_hal::usb::UsbBus::new(
pac.USBCTRL_REGS,
pac.USBCTRL_DPRAM,
clocks.usb_clock,
@ -406,9 +409,11 @@ fn main() -> ! {
.build(&usb_bus);
let mut usb_dev = UsbDeviceBuilder::new(&usb_bus, UsbVidPid(0x1209, 0x0002))
.manufacturer("CMtec")
.product("CMDR Joystick 25")
.serial_number("0001")
.strings(&[StringDescriptors::default()
.manufacturer("CMtec")
.product("CMDR Joystick 25")
.serial_number("0001")])
.unwrap()
.build();
// Read calibration data from eeprom
@ -678,9 +683,8 @@ fn update_status_led<P, SM, I>(
calibration_active: &bool,
throttle_hold_enable: &bool,
) where
P: PIOExt + FunctionConfig,
I: PinId,
Function<P>: ValidPinMode<I>,
I: AnyPin<Function = P::PinFunction>,
P: PIOExt,
SM: StateMachineIndex,
{
if *calibration_active {

View File

@ -5,10 +5,10 @@
//! License: Please refer to LICENSE in root directory
use rp2040_hal::{
gpio::{Function, FunctionConfig, Pin, PinId, ValidPinMode},
pio::{PIOExt, StateMachineIndex, UninitStateMachine, PIO},
gpio::AnyPin,
pio::{PIO, PIOExt, StateMachineIndex, UninitStateMachine},
};
use smart_leds::{SmartLedsWrite, RGB8};
use smart_leds::{RGB8, SmartLedsWrite};
use ws2812_pio::Ws2812Direct;
/// Status LED modes
@ -35,8 +35,6 @@ pub enum StatusMode {
Bootloader = 9,
}
#[warn(dead_code)]
/// Status LED driver
/// This driver uses the PIO state machine to drive a WS2812 LED
///
/// # Example
@ -51,9 +49,8 @@ pub enum StatusMode {
/// ```
pub struct Ws2812StatusLed<P, SM, I>
where
I: PinId,
P: PIOExt + FunctionConfig,
Function<P>: ValidPinMode<I>,
I: AnyPin<Function = P::PinFunction>,
P: PIOExt,
SM: StateMachineIndex,
{
ws2812_direct: Ws2812Direct<P, SM, I>,
@ -63,9 +60,8 @@ where
impl<P, SM, I> Ws2812StatusLed<P, SM, I>
where
I: PinId,
P: PIOExt + FunctionConfig,
Function<P>: ValidPinMode<I>,
I: AnyPin<Function = P::PinFunction>,
P: PIOExt,
SM: StateMachineIndex,
{
/// Creates a new instance of this driver.
@ -77,7 +73,7 @@ where
/// * `sm` - PIO state machine
/// * `clock_freq` - PIO clock frequency
pub fn new(
pin: Pin<I, Function<P>>,
pin: I,
pio: &mut PIO<P>,
sm: UninitStateMachine<(P, SM)>,
clock_freq: fugit::HertzU32,
@ -99,7 +95,6 @@ where
self.mode
}
#[warn(dead_code)]
/// Update status LED
/// Depending on the mode, the LED will be set to a different colour
///

View File

@ -6,11 +6,11 @@
use core::default::Default;
use fugit::ExtU32;
// use packed_struct::prelude::*;
use usb_device::bus::UsbBus;
use usb_device::class_prelude::UsbBusAllocator;
use usbd_human_interface_device::usb_class::prelude::*;
// Fetched from https://github.com/embassy-rs/embassy/blob/e3efda2249640e0b4881289aa609c96a26a7479a/embassy-hal-common/src/fmt.rs
#[cfg(feature = "defmt")]
macro_rules! unwrap {
($($x:tt)*) => {
@ -68,7 +68,7 @@ impl<T, E> Try for Result<T, E> {
}
// Based on example device from https://github.com/dlkj/usbd-human-interface-device/blob/main/src/device/joystick.rs
// Updated to 6x 12bit axis, 25x buttons and 4x hat switches
// Updated to 6x 12bit axis, 32x buttons and 4x hat switches
#[rustfmt::skip]
pub const JOYSTICK_DESCRIPTOR: &[u8] = &[
0x05, 0x01, // Usage Page (Generic Desktop)
@ -131,12 +131,11 @@ pub struct Joystick<'a, B: UsbBus> {
interface: Interface<'a, B, InBytes16, OutNone, ReportSingle>,
}
impl<'a, B: UsbBus> Joystick<'a, B> {
impl<B: UsbBus> Joystick<'_, B> {
pub fn write_report(&mut self, report: &JoystickReport) -> Result<(), UsbHidError> {
let mut data: [u8; 15] = [0; 15];
// Did not make the packed struct work, so doing it manually
// TODO: make this work with packed struct
data[0] = report.x as u8;
data[1] = ((report.x >> 8) as u8) | ((report.y << 4) as u8);
data[2] = (report.y >> 4) as u8;
@ -178,14 +177,16 @@ pub struct JoystickConfig<'a> {
interface: InterfaceConfig<'a, InBytes16, OutNone, ReportSingle>,
}
impl<'a> Default for JoystickConfig<'a> {
impl Default for JoystickConfig<'_> {
#[must_use]
fn default() -> Self {
Self::new(
unwrap!(unwrap!(InterfaceBuilder::new(JOYSTICK_DESCRIPTOR))
.boot_device(InterfaceProtocol::None)
.description("Joystick")
.in_endpoint(10.millis()))
unwrap!(
unwrap!(InterfaceBuilder::new(JOYSTICK_DESCRIPTOR))
.boot_device(InterfaceProtocol::None)
.description("Joystick")
.in_endpoint(10.millis())
)
.without_out_endpoint()
.build(),
)