Skip to main content

ch32_hal/
crc.rs

1//! CRC-32 calculation unit.
2//!
3//! Polynomial `0x04C11DB7`, initial value `0xFFFF_FFFF`, MSB-first words.
4//! No reflection or final XOR.
5//!
6//! The API follows embassy-stm32's `crc` module: [`Crc::feed_word`] and
7//! [`Crc::feed_words`] return the new remainder, [`Crc::read`] returns it
8//! without feeding.
9
10use crate::peripheral::RccPeripheral;
11use crate::{pac, peripherals, Peri, PeripheralType};
12
13/// CRC-32 driver.
14pub struct Crc<'d, T: Instance> {
15    _inner: Peri<'d, T>,
16}
17
18impl<'d, T: Instance> Crc<'d, T> {
19    /// Enable the peripheral clock and start a new calculation at `0xFFFF_FFFF`.
20    pub fn new(inner: Peri<'d, T>) -> Self {
21        T::enable_and_reset();
22        let mut crc = Self { _inner: inner };
23        crc.reset();
24        crc
25    }
26
27    /// Reset the CRC accumulator to `0xFFFF_FFFF` without changing the independent data register.
28    pub fn reset(&mut self) {
29        T::regs().ctlr().write(|w| w.set_reset(true));
30        // RESET is self-clearing; wait for the accumulator before feeding a new word.
31        while T::regs().datar().read().dr() != 0xffff_ffff {}
32    }
33
34    /// Feed a 32-bit word, most-significant bit first, and return the new CRC.
35    pub fn feed_word(&mut self, word: u32) -> u32 {
36        T::regs().datar().write(|w| w.set_dr(word));
37        self.read()
38    }
39
40    /// Feed the words in slice order without resetting the accumulator and
41    /// return the new CRC.
42    pub fn feed_words(&mut self, words: &[u32]) -> u32 {
43        for &word in words {
44            T::regs().datar().write(|w| w.set_dr(word));
45        }
46        self.read()
47    }
48
49    /// Read the raw CRC remainder without resetting the accumulator.
50    pub fn read(&self) -> u32 {
51        T::regs().datar().read().dr()
52    }
53
54    /// Store a byte in the independent data register.
55    ///
56    /// This byte is not included in the CRC calculation and survives [`Self::reset`].
57    pub fn set_independent_data(&mut self, value: u8) {
58        T::regs().idatar().write(|w| w.set_idr(value));
59    }
60
61    /// Read the independent data register; it does not affect the CRC calculation.
62    pub fn independent_data(&self) -> u8 {
63        T::regs().idatar().read().idr()
64    }
65}
66
67trait SealedInstance {
68    fn regs() -> pac::crc::Crc;
69}
70
71/// CRC peripheral instance.
72#[allow(private_bounds)]
73pub trait Instance: SealedInstance + RccPeripheral + PeripheralType + 'static {}
74
75impl<'d, T: Instance> Drop for Crc<'d, T> {
76    fn drop(&mut self) {
77        T::disable();
78    }
79}
80
81foreach_peripheral!(
82    (crc, $inst:ident) => {
83        impl SealedInstance for peripherals::$inst {
84            fn regs() -> pac::crc::Crc {
85                pac::$inst
86            }
87        }
88
89        impl Instance for peripherals::$inst {}
90    };
91);