Skip to main content

es8311_ng/
lib.rs

1//! # Everest Semiconductor ES8311 audio codec driver
2//!
3//! > A platform-agnostic driver to configure the Everest Semiconductor ES8311 mono audio
4//! > codec over I²C.
5//!
6//! This driver was built using [`embedded-hal`] 1.0 and [`es8311-registers`]. Enable the
7//! `async` feature for an equivalent driver on [`embedded-hal-async`] in the `asynch` module.
8//!
9//! The driver only configures the codec. Audio data flows over I²S, which the host drives:
10//! the codec runs in slave mode, with `MCLK`, `SCLK` and `LRCK` supplied by the host.
11//!
12//! ## Safe defaults
13//!
14//! After [`Es8311::init`], the DAC is muted at minimum volume and all analog blocks are
15//! powered down. Nothing reaches the output until [`Es8311::dac_power_up`] and
16//! `set_mute(false)`. Boards with an always-on speaker amplifier play sound as soon as
17//! the DAC is unmuted.
18//!
19//! ## Volume limit
20//!
21//! [`Es8311::set_volume`] never writes a value above [`Es8311::max_volume`]. The limit
22//! defaults to the chip's full scale, [`DAC_VOLUME_MAX`] (+32 dB). Lower it with
23//! [`Es8311::set_max_volume`] when an amplifier after the codec adds gain, so the speaker
24//! or the amplifier cannot be overdriven. On the Kode Dot, with an NS4150B class-D
25//! amplifier, the limit is `0xA9` (-11 dB).
26//!
27//! The raw register access ([`Es8311::write_register`]) bypasses the limit.
28//!
29//! [`embedded-hal`]: https://crates.io/crates/embedded-hal
30//! [`embedded-hal-async`]: https://crates.io/crates/embedded-hal-async
31//! [`es8311-registers`]: https://crates.io/crates/es8311-registers
32
33#![deny(missing_docs)]
34#![no_std]
35#![forbid(unsafe_code)]
36// Enables the `doc_cfg` feature when the `docsrs` configuration attribute is defined.
37#![cfg_attr(docsrs, feature(doc_cfg))]
38
39#[cfg(feature = "async")]
40#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
41pub mod asynch;
42mod clock;
43mod sequence;
44
45pub use es8311_registers as registers;
46pub use es8311_registers::{
47    ALTERNATE_DEVICE_ADDRESS, DEFAULT_DEVICE_ADDRESS, SerialFormat, WordLength,
48};
49
50use embedded_hal::delay::DelayNs;
51use embedded_hal::i2c::I2c;
52use es8311_registers::prelude::*;
53use es8311_registers::{ChipId1, ChipId2, ChipVersion, DacControl, DacVolume};
54use sequence::Write;
55
56/// The ID read from [`ChipId1`] and [`ChipId2`] (`0xFD`, `0xFE`) of an ES8311.
57pub const ES8311_CHIP_ID: u16 =
58    u16::from_be_bytes([registers::ES8311_CHIP_ID1, registers::ES8311_CHIP_ID2]);
59
60/// The highest [`DacVolume`] value: +32 dB.
61pub const DAC_VOLUME_MAX: u8 = 0xFF;
62
63/// The [`DacVolume`] value for 0 dB. Each step is 0.5 dB.
64pub const DAC_VOLUME_0DB: u8 = 0xBF;
65
66/// How long [`Es8311::init`] holds the digital blocks in reset, in milliseconds.
67///
68/// The user guide (section 9.1) suggests "several milliseconds".
69pub const RESET_DELAY_MS: u32 = 5;
70
71/// The audio interface configuration.
72#[derive(Debug, Copy, Clone, PartialEq, Eq)]
73#[cfg_attr(feature = "defmt", derive(defmt::Format))]
74pub struct Config {
75    /// The frequency on the `MCLK` pin, in Hz.
76    pub mclk_hz: u32,
77    /// The sample rate (`LRCK`), in Hz.
78    pub sample_rate_hz: u32,
79    /// The serial data format, for both directions.
80    pub format: SerialFormat,
81    /// The serial data word length, for both directions.
82    pub word_length: WordLength,
83}
84
85impl Config {
86    /// I²S with 16-bit words at the specified sample rate and MCLK = 256 × fs.
87    pub const fn new(sample_rate_hz: u32) -> Self {
88        Self {
89            mclk_hz: sample_rate_hz * 256,
90            sample_rate_hz,
91            format: SerialFormat::I2s,
92            word_length: WordLength::Bits16,
93        }
94    }
95
96    /// Sets the frequency on the `MCLK` pin, in Hz.
97    pub const fn with_mclk(self, mclk_hz: u32) -> Self {
98        Self { mclk_hz, ..self }
99    }
100
101    /// Sets the serial data format.
102    pub const fn with_format(self, format: SerialFormat) -> Self {
103        Self { format, ..self }
104    }
105
106    /// Sets the serial data word length.
107    pub const fn with_word_length(self, word_length: WordLength) -> Self {
108        Self {
109            word_length,
110            ..self
111        }
112    }
113}
114
115/// A driver error.
116#[derive(Debug, Copy, Clone, PartialEq, Eq)]
117#[cfg_attr(feature = "defmt", derive(defmt::Format))]
118pub enum Error<E> {
119    /// The I²C transfer failed.
120    I2c(E),
121    /// The chip ID is not [`ES8311_CHIP_ID`].
122    UnknownChip(u16),
123    /// No clock coefficients exist for this MCLK frequency and sample rate.
124    UnsupportedClock,
125}
126
127/// Checks the configuration before any bus access.
128fn coefficients<E>(config: &Config) -> Result<&'static clock::ClockCoefficients, Error<E>> {
129    clock::lookup(config.mclk_hz, config.sample_rate_hz).ok_or(Error::UnsupportedClock)
130}
131
132/// ES8311 driver.
133#[derive(Debug)]
134pub struct Es8311<I2C> {
135    i2c: I2C,
136    address: u8,
137    max_volume: u8,
138}
139
140impl<I2C> Es8311<I2C>
141where
142    I2C: I2c,
143{
144    /// Creates a driver for a chip at [`DEFAULT_DEVICE_ADDRESS`]. Performs no bus access.
145    pub fn new(i2c: I2C) -> Self {
146        Self::with_address(i2c, DEFAULT_DEVICE_ADDRESS)
147    }
148
149    /// Creates a driver for a chip at the specified 7-bit address. Performs no bus access.
150    pub fn with_address(i2c: I2C, address: u8) -> Self {
151        Self {
152            i2c,
153            address,
154            max_volume: DAC_VOLUME_MAX,
155        }
156    }
157
158    /// Consumes the driver and returns the I²C bus.
159    pub fn release(self) -> I2C {
160        self.i2c
161    }
162
163    /// Reads the chip ID from `0xFD` and `0xFE`.
164    pub fn chip_id(&mut self) -> Result<u16, I2C::Error> {
165        let high = self.read_register::<ChipId1>()?.value();
166        let low = self.read_register::<ChipId2>()?.value();
167        Ok(u16::from_be_bytes([high, low]))
168    }
169
170    /// Reads the chip version from `0xFF`.
171    pub fn chip_version(&mut self) -> Result<u8, I2C::Error> {
172        Ok(self.read_register::<ChipVersion>()?.value())
173    }
174
175    /// Checks whether the chip ID matches [`ES8311_CHIP_ID`].
176    pub fn identify(&mut self) -> Result<bool, I2C::Error> {
177        Ok(self.chip_id()? == ES8311_CHIP_ID)
178    }
179
180    /// Resets and configures the codec as an I²S slave clocked from `MCLK`.
181    ///
182    /// Checks the chip ID, resets the digital blocks for [`RESET_DELAY_MS`], then sets
183    /// the clock dividers, the serial format and the output driver. Disables the
184    /// ADC-to-DAC and DAC-to-`ASDOUT` loopbacks. Leaves the DAC muted at minimum volume
185    /// and all analog blocks powered down.
186    ///
187    /// Fails with [`Error::UnsupportedClock`] before any bus access if the clock
188    /// configuration is not supported. Call again to leave [`standby`](Self::standby).
189    pub fn init<D: DelayNs>(
190        &mut self,
191        delay: &mut D,
192        config: &Config,
193    ) -> Result<(), Error<I2C::Error>> {
194        let clock = coefficients(config)?;
195        let id = self.chip_id().map_err(Error::I2c)?;
196
197        if id != ES8311_CHIP_ID {
198            return Err(Error::UnknownChip(id));
199        }
200
201        self.write_all(&sequence::RESET).map_err(Error::I2c)?;
202        delay.delay_ms(RESET_DELAY_MS);
203        self.write_all(&sequence::configure(config, clock))
204            .map_err(Error::I2c)
205    }
206
207    /// Powers up the analog circuits and the DAC. The mute state is unchanged.
208    pub fn dac_power_up(&mut self) -> Result<(), I2C::Error> {
209        self.write_all(&sequence::DAC_POWER_UP)
210    }
211
212    /// Mutes the DAC, then powers down the DAC and the analog circuits.
213    pub fn dac_power_down(&mut self) -> Result<(), I2C::Error> {
214        self.set_mute(true)?;
215        self.write_all(&sequence::DAC_POWER_DOWN)
216    }
217
218    /// Mutes or unmutes the DAC.
219    pub fn set_mute(&mut self, mute: bool) -> Result<(), I2C::Error> {
220        self.modify_register(|r: DacControl| r.with_dac_dsmmute(mute).with_dac_demmute(mute))
221    }
222
223    /// The highest value [`set_volume`](Self::set_volume) writes.
224    pub fn max_volume(&self) -> u8 {
225        self.max_volume
226    }
227
228    /// Sets the highest value [`set_volume`](Self::set_volume) writes.
229    ///
230    /// Lowers the current volume to the new limit if it is above it.
231    pub fn set_max_volume(&mut self, max: u8) -> Result<(), I2C::Error> {
232        self.max_volume = max;
233
234        if self.volume()? > max {
235            self.write_register(DacVolume::new().with_value(max))?;
236        }
237
238        Ok(())
239    }
240
241    /// Sets the DAC volume, clamped to [`max_volume`](Self::max_volume).
242    ///
243    /// `0x00` is -95.5 dB, [`DAC_VOLUME_0DB`] is 0 dB and each step is 0.5 dB.
244    pub fn set_volume(&mut self, volume: u8) -> Result<(), I2C::Error> {
245        self.write_register(DacVolume::new().with_value(volume.min(self.max_volume)))
246    }
247
248    /// Reads the DAC volume.
249    pub fn volume(&mut self) -> Result<u8, I2C::Error> {
250        Ok(self.read_register::<DacVolume>()?.value())
251    }
252
253    /// Mutes the DAC and enters low-power standby: powers down all analog blocks, stops
254    /// the clocks and holds the digital blocks in reset. Call [`init`](Self::init) to
255    /// leave standby.
256    pub fn standby(&mut self) -> Result<(), I2C::Error> {
257        self.set_mute(true)?;
258        self.write_all(&sequence::STANDBY)
259    }
260
261    /// Reads a single register.
262    pub fn read_register<R>(&mut self) -> Result<R, I2C::Error>
263    where
264        R: ReadableRegister,
265    {
266        let mut buffer = [0];
267        self.i2c
268            .write_read(self.address, &[*R::REGISTER_ADDRESS], &mut buffer)?;
269        Ok(R::from_bits(buffer[0]))
270    }
271
272    /// Writes a single register.
273    pub fn write_register<R>(&mut self, register: R) -> Result<(), I2C::Error>
274    where
275        R: WritableRegister,
276    {
277        self.i2c
278            .write(self.address, &[*R::REGISTER_ADDRESS, register.to_bits()])
279    }
280
281    /// Reads, modifies and writes back a single register.
282    pub fn modify_register<R, F>(&mut self, f: F) -> Result<(), I2C::Error>
283    where
284        R: ReadableRegister + WritableRegister,
285        F: FnOnce(R) -> R,
286    {
287        let register = self.read_register::<R>()?;
288        self.write_register(f(register))
289    }
290
291    fn write_all(&mut self, writes: &[Write]) -> Result<(), I2C::Error> {
292        for &(reg, value) in writes {
293            self.i2c.write(self.address, &[reg.addr(), value])?;
294        }
295
296        Ok(())
297    }
298}