Skip to content

bxCAN impl #224

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ edition = "2018"
cortex-m = "0.6.3"
nb = "0.1.1"
stm32l4 = "0.13.0"
bxcan = "0.5"

[dependencies.rand_core]
version = "0.6.2"
Expand Down Expand Up @@ -99,6 +100,10 @@ lto = true
name = "adc"
required-features = ["rt", "stm32l4x3"]

[[example]]
name = "can-loopback"
required-features = ["rt", "stm32l4x1"]

[[example]]
name = "irq_button"
required-features = ["rt"]
Expand Down
94 changes: 94 additions & 0 deletions examples/can-loopback.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
//! Run the bxCAN peripheral in loopback mode.

#![deny(unsafe_code)]
#![deny(warnings)]
#![no_main]
#![no_std]

use bxcan::{
filter::Mask32,
{Frame, StandardId},
};
use panic_halt as _;
use rtic::app;
use rtt_target::{rprintln, rtt_init_print};
use stm32l4xx_hal::{can::Can, prelude::*};

#[app(device = stm32l4xx_hal::stm32, peripherals = true)]
const APP: () = {
#[init]
fn init(cx: init::Context) {
rtt_init_print!();

let dp = cx.device;

let mut flash = dp.FLASH.constrain();
let mut rcc = dp.RCC.constrain();
let mut pwr = dp.PWR.constrain(&mut rcc.apb1r1);
let mut gpioa = dp.GPIOA.split(&mut rcc.ahb2);

// Set the clocks to 80 MHz
let _clocks = rcc.cfgr.sysclk(80.mhz()).freeze(&mut flash.acr, &mut pwr);

rprintln!(" - CAN init");

let mut can = {
let rx = gpioa.pa11.into_af9(&mut gpioa.moder, &mut gpioa.afrh);
let tx = gpioa.pa12.into_af9(&mut gpioa.moder, &mut gpioa.afrh);

let can = Can::new(&mut rcc.apb1r1, dp.CAN1, (tx, rx));

bxcan::Can::new(can)
};
can.configure(|config| {
// APB1 (PCLK1): 80 MHz, Bit rate: 100kBit/s, Sample Point 87.5%
// Value was calculated with http://www.bittiming.can-wiki.info/
config.set_bit_timing(0x001c_0031);
config.set_loopback(true);
});

// Configure filters so that can frames can be received.
let mut filters = can.modify_filters();
filters.enable_bank(0, Mask32::accept_all());

// Drop filters to leave filter configuraiton mode.
drop(filters);

// Enable and wait for bxCAN sync to bus
while let Err(_) = can.enable() {}

// Send a frame
let mut test: [u8; 8] = [0; 8];
let id: u16 = 0x500;

test[0] = 72;
test[1] = 1;
test[2] = 2;
test[3] = 3;
test[4] = 4;
test[5] = 5;
test[6] = 6;
test[7] = 7;
let test_frame = Frame::new_data(StandardId::new(id).unwrap(), test);
can.transmit(&test_frame).unwrap();

// Wait for TX to finish
while !can.is_transmitter_idle() {}

rprintln!(" - CAN tx complete: {:?}", test_frame);

// Receive the packet back
let r = can.receive();

rprintln!(" - CAN rx {:?}", r);

assert_eq!(Ok(test_frame), r);
}

#[idle]
fn idle(_: idle::Context) -> ! {
loop {
continue;
}
}
};
107 changes: 107 additions & 0 deletions src/can.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
//! # Controller Area Network (CAN) Interface
//!
//! Based on STM32F4xx HAL.

use crate::pac::CAN1;
use crate::rcc::APB1R1;

mod sealed {
pub trait Sealed {}
}

/// A pair of (TX, RX) pins configured for CAN communication
pub trait Pins: sealed::Sealed {
/// The CAN peripheral that uses these pins
type Instance;
}

/// Implements sealed::Sealed and Pins for a (TX, RX) pair of pins associated with a CAN peripheral
/// The alternate function number can be specified after each pin name.
macro_rules! pins {
($($PER:ident => ($tx:ident<$txaf:ident>, $rx:ident<$rxaf:ident>),)+) => {
$(
impl crate::can::sealed::Sealed for ($tx<crate::gpio::Alternate<$txaf, Input<Floating>>>, $rx<crate::gpio::Alternate<$rxaf, Input<Floating>>>) {}
impl crate::can::Pins for ($tx<crate::gpio::Alternate<$txaf, Input<Floating>>>, $rx<crate::gpio::Alternate<$rxaf, Input<Floating>>>) {
type Instance = $PER;
}
)+
}
}

mod common_pins {
use crate::gpio::{
gpioa::{PA11, PA12},
gpiob::{PB8, PB9},
gpiod::{PD0, PD1},
Floating, Input, AF9,
};
use crate::pac::CAN1;

// All STM32L4 models with CAN support these pins
pins! {
CAN1 => (PA12<AF9>, PA11<AF9>),
CAN1 => (PD1<AF9>, PD0<AF9>),
CAN1 => (PB9<AF9>, PB8<AF9>),
}
}

#[cfg(feature = "stm32l4x1")]
mod pb13_pb12_af10 {
use crate::gpio::{
gpiob::{PB12, PB13},
Floating, Input, AF10,
};
use crate::pac::CAN1;
pins! { CAN1 => (PB13<AF10>, PB12<AF10>), }
}

/// Enable/disable peripheral
pub trait Enable: sealed::Sealed {
/// Enables this peripheral by setting the associated enable bit in an RCC enable register
fn enable(apb: &mut APB1R1);
}

impl crate::can::sealed::Sealed for crate::pac::CAN1 {}

impl crate::can::Enable for crate::pac::CAN1 {
#[inline(always)]
fn enable(apb: &mut APB1R1) {
// Enable peripheral clock
apb.enr().modify(|_, w| w.can1en().set_bit());
apb.rstr().modify(|_, w| w.can1rst().set_bit());
apb.rstr().modify(|_, w| w.can1rst().clear_bit());
}
}

/// Interface to the CAN peripheral.
pub struct Can<Instance, Pins> {
can: Instance,
pins: Pins,
}

impl<Instance, P> Can<Instance, P>
where
Instance: Enable,
P: Pins<Instance = Instance>,
{
/// Creates a CAN interface.
pub fn new(apb: &mut APB1R1, can: Instance, pins: P) -> Can<Instance, P> {
Instance::enable(apb);
Can { can, pins }
}

// Split the peripheral back into its components.
pub fn split(self) -> (Instance, P) {
(self.can, self.pins)
}
}

unsafe impl<Pins> bxcan::Instance for Can<CAN1, Pins> {
const REGISTERS: *mut bxcan::RegisterBlock = CAN1::ptr() as *mut _;
}

unsafe impl<Pins> bxcan::FilterOwner for Can<CAN1, Pins> {
const NUM_FILTER_BANKS: u8 = 14;
}

unsafe impl<Pins> bxcan::MasterInstance for Can<CAN1, Pins> {}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ pub mod traits;
feature = "stm32l4x6"
))]
pub mod adc;
#[cfg(any(feature = "stm32l4x1", feature = "stm32l4x5",))]
pub mod can;
#[cfg(any(
feature = "stm32l4x1",
feature = "stm32l4x2",
Expand Down