-
Notifications
You must be signed in to change notification settings - Fork 620
/
i2s.rs
322 lines (280 loc) · 9.9 KB
/
i2s.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
//! Inter-IC Sound (I2S)
use embassy_hal_internal::into_ref;
use crate::gpio::{AFType, AnyPin, SealedPin};
use crate::mode::Async;
use crate::pac::spi::vals;
use crate::spi::{Config as SpiConfig, *};
use crate::time::Hertz;
use crate::{Peripheral, PeripheralRef};
/// I2S mode
#[derive(Copy, Clone)]
pub enum Mode {
/// Master mode
Master,
/// Slave mode
Slave,
}
/// I2S function
#[derive(Copy, Clone)]
pub enum Function {
/// Transmit audio data
Transmit,
/// Receive audio data
Receive,
}
/// I2C standard
#[derive(Copy, Clone)]
pub enum Standard {
/// Philips
Philips,
/// Most significant bit first.
MsbFirst,
/// Least significant bit first.
LsbFirst,
/// PCM with long sync.
PcmLongSync,
/// PCM with short sync.
PcmShortSync,
}
impl Standard {
#[cfg(any(spi_v1, spi_f1))]
const fn i2sstd(&self) -> vals::I2sstd {
match self {
Standard::Philips => vals::I2sstd::PHILIPS,
Standard::MsbFirst => vals::I2sstd::MSB,
Standard::LsbFirst => vals::I2sstd::LSB,
Standard::PcmLongSync => vals::I2sstd::PCM,
Standard::PcmShortSync => vals::I2sstd::PCM,
}
}
#[cfg(any(spi_v1, spi_f1))]
const fn pcmsync(&self) -> vals::Pcmsync {
match self {
Standard::PcmLongSync => vals::Pcmsync::LONG,
_ => vals::Pcmsync::SHORT,
}
}
}
/// I2S data format.
#[derive(Copy, Clone)]
pub enum Format {
/// 16 bit data length on 16 bit wide channel
Data16Channel16,
/// 16 bit data length on 32 bit wide channel
Data16Channel32,
/// 24 bit data length on 32 bit wide channel
Data24Channel32,
/// 32 bit data length on 32 bit wide channel
Data32Channel32,
}
impl Format {
#[cfg(any(spi_v1, spi_f1))]
const fn datlen(&self) -> vals::Datlen {
match self {
Format::Data16Channel16 => vals::Datlen::BITS16,
Format::Data16Channel32 => vals::Datlen::BITS16,
Format::Data24Channel32 => vals::Datlen::BITS24,
Format::Data32Channel32 => vals::Datlen::BITS32,
}
}
#[cfg(any(spi_v1, spi_f1))]
const fn chlen(&self) -> vals::Chlen {
match self {
Format::Data16Channel16 => vals::Chlen::BITS16,
Format::Data16Channel32 => vals::Chlen::BITS32,
Format::Data24Channel32 => vals::Chlen::BITS32,
Format::Data32Channel32 => vals::Chlen::BITS32,
}
}
}
/// Clock polarity
#[derive(Copy, Clone)]
pub enum ClockPolarity {
/// Low on idle.
IdleLow,
/// High on idle.
IdleHigh,
}
impl ClockPolarity {
#[cfg(any(spi_v1, spi_f1))]
const fn ckpol(&self) -> vals::Ckpol {
match self {
ClockPolarity::IdleHigh => vals::Ckpol::IDLEHIGH,
ClockPolarity::IdleLow => vals::Ckpol::IDLELOW,
}
}
}
/// [`I2S`] configuration.
///
/// - `MS`: `Master` or `Slave`
/// - `TR`: `Transmit` or `Receive`
/// - `STD`: I2S standard, eg `Philips`
/// - `FMT`: Frame Format marker, eg `Data16Channel16`
#[non_exhaustive]
#[derive(Copy, Clone)]
pub struct Config {
/// Mode
pub mode: Mode,
/// Function (transmit, receive)
pub function: Function,
/// Which I2S standard to use.
pub standard: Standard,
/// Data format.
pub format: Format,
/// Clock polarity.
pub clock_polarity: ClockPolarity,
/// True to eanble master clock output from this instance.
pub master_clock: bool,
}
impl Default for Config {
fn default() -> Self {
Self {
mode: Mode::Master,
function: Function::Transmit,
standard: Standard::Philips,
format: Format::Data16Channel16,
clock_polarity: ClockPolarity::IdleLow,
master_clock: true,
}
}
}
/// I2S driver.
pub struct I2S<'d, T: Instance> {
_peri: Spi<'d, T, Async>,
sd: Option<PeripheralRef<'d, AnyPin>>,
ws: Option<PeripheralRef<'d, AnyPin>>,
ck: Option<PeripheralRef<'d, AnyPin>>,
mck: Option<PeripheralRef<'d, AnyPin>>,
}
impl<'d, T: Instance> I2S<'d, T> {
/// Note: Full-Duplex modes are not supported at this time
pub fn new(
peri: impl Peripheral<P = T> + 'd,
sd: impl Peripheral<P = impl MosiPin<T>> + 'd,
ws: impl Peripheral<P = impl WsPin<T>> + 'd,
ck: impl Peripheral<P = impl CkPin<T>> + 'd,
mck: impl Peripheral<P = impl MckPin<T>> + 'd,
txdma: impl Peripheral<P = impl TxDma<T>> + 'd,
rxdma: impl Peripheral<P = impl RxDma<T>> + 'd,
freq: Hertz,
config: Config,
) -> Self {
into_ref!(sd, ws, ck, mck);
sd.set_as_af(sd.af_num(), AFType::OutputPushPull);
sd.set_speed(crate::gpio::Speed::VeryHigh);
ws.set_as_af(ws.af_num(), AFType::OutputPushPull);
ws.set_speed(crate::gpio::Speed::VeryHigh);
ck.set_as_af(ck.af_num(), AFType::OutputPushPull);
ck.set_speed(crate::gpio::Speed::VeryHigh);
mck.set_as_af(mck.af_num(), AFType::OutputPushPull);
mck.set_speed(crate::gpio::Speed::VeryHigh);
let mut spi_cfg = SpiConfig::default();
spi_cfg.frequency = freq;
let spi = Spi::new_internal(peri, txdma, rxdma, spi_cfg);
// TODO move i2s to the new mux infra.
//#[cfg(all(rcc_f4, not(stm32f410)))]
//let pclk = unsafe { get_freqs() }.plli2s1_q.unwrap();
//#[cfg(stm32f410)]
let pclk = T::frequency();
let (odd, div) = compute_baud_rate(pclk, freq, config.master_clock, config.format);
#[cfg(any(spi_v1, spi_f1))]
{
use stm32_metapac::spi::vals::{I2scfg, Odd};
// 1. Select the I2SDIV[7:0] bits in the SPI_I2SPR register to define the serial clock baud
// rate to reach the proper audio sample frequency. The ODD bit in the SPI_I2SPR
// register also has to be defined.
T::REGS.i2spr().modify(|w| {
w.set_i2sdiv(div);
w.set_odd(match odd {
true => Odd::ODD,
false => Odd::EVEN,
});
w.set_mckoe(config.master_clock);
});
// 2. Select the CKPOL bit to define the steady level for the communication clock. Set the
// MCKOE bit in the SPI_I2SPR register if the master clock MCK needs to be provided to
// the external DAC/ADC audio component (the I2SDIV and ODD values should be
// computed depending on the state of the MCK output, for more details refer to
// Section 28.4.4: Clock generator).
// 3. Set the I2SMOD bit in SPI_I2SCFGR to activate the I2S functionalities and choose the
// I2S standard through the I2SSTD[1:0] and PCMSYNC bits, the data length through the
// DATLEN[1:0] bits and the number of bits per channel by configuring the CHLEN bit.
// Select also the I2S master mode and direction (Transmitter or Receiver) through the
// I2SCFG[1:0] bits in the SPI_I2SCFGR register.
// 4. If needed, select all the potential interruption sources and the DMA capabilities by
// writing the SPI_CR2 register.
// 5. The I2SE bit in SPI_I2SCFGR register must be set.
T::REGS.i2scfgr().modify(|w| {
w.set_ckpol(config.clock_polarity.ckpol());
w.set_i2smod(true);
w.set_i2sstd(config.standard.i2sstd());
w.set_pcmsync(config.standard.pcmsync());
w.set_datlen(config.format.datlen());
w.set_chlen(config.format.chlen());
w.set_i2scfg(match (config.mode, config.function) {
(Mode::Master, Function::Transmit) => I2scfg::MASTERTX,
(Mode::Master, Function::Receive) => I2scfg::MASTERRX,
(Mode::Slave, Function::Transmit) => I2scfg::SLAVETX,
(Mode::Slave, Function::Receive) => I2scfg::SLAVERX,
});
w.set_i2se(true)
});
}
Self {
_peri: spi,
sd: Some(sd.map_into()),
ws: Some(ws.map_into()),
ck: Some(ck.map_into()),
mck: Some(mck.map_into()),
}
}
/// Write audio data.
pub async fn write<W: Word>(&mut self, data: &[W]) -> Result<(), Error> {
self._peri.write(data).await
}
/// Read audio data.
pub async fn read<W: Word>(&mut self, data: &mut [W]) -> Result<(), Error> {
self._peri.read(data).await
}
}
impl<'d, T: Instance> Drop for I2S<'d, T> {
fn drop(&mut self) {
self.sd.as_ref().map(|x| x.set_as_disconnected());
self.ws.as_ref().map(|x| x.set_as_disconnected());
self.ck.as_ref().map(|x| x.set_as_disconnected());
self.mck.as_ref().map(|x| x.set_as_disconnected());
}
}
// Note, calculation details:
// Fs = i2s_clock / [256 * ((2 * div) + odd)] when master clock is enabled
// Fs = i2s_clock / [(channel_length * 2) * ((2 * div) + odd)]` when master clock is disabled
// channel_length is 16 or 32
//
// can be rewritten as
// Fs = i2s_clock / (coef * division)
// where coef is a constant equal to 256, 64 or 32 depending channel length and master clock
// and where division = (2 * div) + odd
//
// Equation can be rewritten as
// division = i2s_clock/ (coef * Fs)
//
// note: division = (2 * div) + odd = (div << 1) + odd
// in other word, from bits point of view, division[8:1] = div[7:0] and division[0] = odd
fn compute_baud_rate(i2s_clock: Hertz, request_freq: Hertz, mclk: bool, data_format: Format) -> (bool, u8) {
let coef = if mclk {
256
} else if let Format::Data16Channel16 = data_format {
32
} else {
64
};
let (n, d) = (i2s_clock.0, coef * request_freq.0);
let division = (n + (d >> 1)) / d;
if division < 4 {
(false, 2)
} else if division > 511 {
(true, 255)
} else {
((division & 1) == 1, (division >> 1) as u8)
}
}