daisy-embassy 0.3.0

async audio development with daisy seed and embassy
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Driver for the IS25LP064 Flash chip connected via QSPI
//! Note:
//! The Daisy bootloader (as of v6.3) Does not use QPI mode, and configuring the flash chip that way would cause problems on reset. So for compatibility's sake, we do not use it here either.
#![allow(unused)]

use crate::hal;
use crate::pins::FlashPins;
use embassy_stm32::{
    Peri,
    dma::{self},
    interrupt::{self, typelevel::Binding},
    mode::{Async, Mode},
    qspi::{
        Instance, InterruptHandler, MatchMode, QuadDma,
        enums::{AddressSize, ChipSelectHighTime, FIFOThresholdLevel, MemorySize},
    },
};
use embassy_time::{Duration, WithTimeout};
use hal::{
    mode::Blocking,
    peripherals::QUADSPI,
    qspi::{
        Qspi, TransferConfig,
        enums::{DummyCycles, QspiWidth},
    },
};

// Commands from IS25LP064 datasheet.
const WRITE_CMD: u8 = 0x32; // PPQ
const WRITE_ENABLE_CMD: u8 = 0x06; // WREN
const SECTOR_ERASE_CMD: u8 = 0xD7; // SER
const FAST_READ_QUAD_IO_CMD: u8 = 0xEB; // FRQIO
const RESET_ENABLE_CMD: u8 = 0x66;
const RESET_MEMORY_CMD: u8 = 0x99;

const WRITE_STATUS_REGISTER_CMD: u8 = 0x01; // WRSR
const READ_STATUS_REGISTER_CMD: u8 = 0x05; // RDSR
const STATUS_BIT_WIP: u8 = 1 << 0;
const STATUS_BIT_WEL: u8 = 1 << 1;
const STATUS_BIT_BP0: u8 = 1 << 2;
const STATUS_BIT_BP1: u8 = 1 << 3;
const STATUS_BIT_BP2: u8 = 1 << 4;
const STATUS_BIT_BP3: u8 = 1 << 5;
const STATUS_BIT_QE: u8 = 1 << 6;
const STATUS_BIT_SRWD: u8 = 1 << 7;

const SET_READ_PARAMETERS_CMD: u8 = 0xC0; // SRP
const READ_PARAMS_BIT_BL0: u8 = 1 << 0;
const READ_PARAMS_BIT_BL1: u8 = 1 << 1;
const READ_PARAMS_BIT_WE: u8 = 1 << 2;
const READ_PARAMS_BIT_DC0: u8 = 1 << 3;
const READ_PARAMS_BIT_DC1: u8 = 1 << 4;
const READ_PARAMS_BIT_ODS0: u8 = 1 << 5;
const READ_PARAMS_BIT_ODS1: u8 = 1 << 6;
const READ_PARAMS_BIT_ODS2: u8 = 1 << 7;

// Memory array specifications as defined in the datasheet.
const SECTOR_SIZE: u32 = 4096;
const PAGE_SIZE: u32 = 256;
const MAX_ADDRESS: u32 = 0x7FFFFF;

// Max Sector Erase time is 300ms
const SECTOR_ERASE_TIMEOUT: Duration = Duration::from_millis(600);

// Max Page Write time is 0.8ms
const PAGE_WRITE_TIMEOUT: Duration = Duration::from_micros(1600);

pub struct FlashBuilder<'a> {
    pub pins: FlashPins<'a>,
    pub qspi: Peri<'a, QUADSPI>,
}

impl<'a> FlashBuilder<'a> {
    pub fn build(self) -> Flash<'a, Blocking> {
        let config = self.config();
        let Self { pins, qspi } = self;

        let qspi = Qspi::new_blocking_bank1(
            qspi, pins.IO0, pins.IO1, pins.IO2, pins.IO3, pins.SCK, pins.CS, config,
        );
        let mut result = Flash { qspi };
        result.reset();
        result
    }

    pub fn build_async<D, I>(self, dma_ch: Peri<'a, D>, irq: I) -> Flash<'a, Async>
    where
        D: QuadDma<QUADSPI>,
        I: Binding<D::Interrupt, dma::InterruptHandler<D>>
            + Binding<<QUADSPI as Instance>::Interrupt, InterruptHandler<QUADSPI>>
            + 'a,
    {
        let config = self.config();
        let Self { pins, qspi } = self;

        let qspi = Qspi::new_bank1(
            qspi, pins.IO0, pins.IO1, pins.IO2, pins.IO3, pins.SCK, pins.CS, dma_ch, irq, config,
        );
        let mut result = Flash { qspi };
        result.reset();
        result
    }

    fn config(&self) -> hal::qspi::Config {
        let mut config = hal::qspi::Config::default();

        config.memory_size = MemorySize::_8MiB;
        config.address_size = AddressSize::_24bit;
        config.prescaler = 1;
        config.cs_high_time = ChipSelectHighTime::_2Cycle;
        config.fifo_threshold = FIFOThresholdLevel::_1Bytes;
        config
    }
}

pub struct Flash<'a, MODE: Mode> {
    qspi: Qspi<'a, QUADSPI, MODE>,
}

impl<MODE: Mode> Flash<'_, MODE> {
    pub fn read(&mut self, address: u32, buffer: &mut [u8]) {
        assert!(address + buffer.len() as u32 <= MAX_ADDRESS);

        let transaction = TransferConfig {
            iwidth: QspiWidth::SING,
            awidth: QspiWidth::QUAD,
            dwidth: QspiWidth::QUAD,
            instruction: FAST_READ_QUAD_IO_CMD,
            address: Some(address),
            dummy: DummyCycles::_8,
        };
        self.qspi.blocking_read(buffer, transaction);
    }

    pub fn read_uuid(&mut self) -> [u8; 16] {
        let mut buffer = [0; 16];
        let transaction: TransferConfig = TransferConfig {
            iwidth: QspiWidth::SING,
            awidth: QspiWidth::SING,
            dwidth: QspiWidth::SING,
            instruction: 0x4B,
            address: Some(0x00),
            dummy: DummyCycles::_8,
        };
        self.qspi.blocking_read(&mut buffer, transaction);
        buffer
    }

    pub fn write(&mut self, mut address: u32, data: &[u8]) {
        assert!(address <= MAX_ADDRESS);
        assert!(!data.is_empty());
        self.erase(address, data.len() as u32);

        let mut length = data.len() as u32;
        let mut start_cursor = 0;

        //WRITE_CMD(or PPQ) allows to write up to 256 bytes, which is as much as PAGE_SIZE.
        //Let's divide the data into chunks of page size to write to flash
        loop {
            // Calculate number of bytes between address and end of the page.
            let page_remainder = PAGE_SIZE - (address & (PAGE_SIZE - 1));
            let size = page_remainder.min(length) as usize;
            self.enable_write();
            let transaction = TransferConfig {
                iwidth: QspiWidth::SING,
                awidth: QspiWidth::SING,
                dwidth: QspiWidth::QUAD,
                instruction: WRITE_CMD,
                address: Some(address),
                dummy: DummyCycles::_0,
            };

            self.qspi
                .blocking_write(&data[start_cursor..start_cursor + size], transaction);
            self.wait_for_write();
            start_cursor += size;

            // Stop if this was the last needed page.
            if length <= page_remainder {
                break;
            }
            length -= page_remainder;

            // Jump to the next page.
            address += page_remainder;
            address %= MAX_ADDRESS;
        }
    }

    pub fn erase(&mut self, mut address: u32, mut length: u32) {
        assert!(address <= MAX_ADDRESS);
        assert!(length > 0);

        loop {
            // Erase the sector.
            self.enable_write();
            let transaction = TransferConfig {
                iwidth: QspiWidth::SING,
                awidth: QspiWidth::SING,
                dwidth: QspiWidth::NONE,
                instruction: SECTOR_ERASE_CMD,
                address: Some(address),
                dummy: DummyCycles::_0,
            };

            self.qspi.blocking_command(transaction);
            self.wait_for_write();

            // Calculate number of bytes between address and end of the sector.
            let sector_remainder = SECTOR_SIZE - (address & (SECTOR_SIZE - 1));

            // Stop if this was the last affected sector.
            if length <= sector_remainder {
                break;
            }
            length -= sector_remainder;

            // Jump to the next sector.
            address += sector_remainder;
            address %= MAX_ADDRESS;
        }
    }

    fn enable_write(&mut self) {
        let transaction = TransferConfig {
            iwidth: QspiWidth::SING,
            awidth: QspiWidth::NONE,
            dwidth: QspiWidth::NONE,
            instruction: WRITE_ENABLE_CMD,
            address: None,
            dummy: DummyCycles::_0,
        };
        self.qspi.blocking_command(transaction);
    }

    fn wait_for_write(&mut self) {
        loop {
            if self.read_status() & STATUS_BIT_WIP == 0 {
                break;
            }
        }
    }

    fn read_status(&mut self) -> u8 {
        let mut status: [u8; 1] = [0xFF; 1];
        let transaction = TransferConfig {
            iwidth: QspiWidth::SING,
            awidth: QspiWidth::NONE,
            dwidth: QspiWidth::SING,
            instruction: READ_STATUS_REGISTER_CMD,
            address: None,
            dummy: DummyCycles::_0,
        };
        self.qspi.blocking_read(&mut status, transaction);
        status[0]
    }

    fn reset_memory(&mut self) {
        let transaction = TransferConfig {
            iwidth: QspiWidth::SING,
            awidth: QspiWidth::NONE,
            dwidth: QspiWidth::NONE,
            instruction: RESET_ENABLE_CMD,
            address: None,
            dummy: DummyCycles::_0,
        };
        self.qspi.blocking_command(transaction);

        let transaction = TransferConfig {
            iwidth: QspiWidth::SING,
            awidth: QspiWidth::NONE,
            dwidth: QspiWidth::NONE,
            instruction: RESET_MEMORY_CMD,
            address: None,
            dummy: DummyCycles::_0,
        };
        self.qspi.blocking_command(transaction);
    }

    /// Reset status registers into driver's defaults. This makes sure that the
    /// peripheral is configured as expected.
    fn reset_status_register(&mut self) {
        self.enable_write();
        let value = STATUS_BIT_QE;
        let transaction = TransferConfig {
            iwidth: QspiWidth::SING,
            awidth: QspiWidth::NONE,
            dwidth: QspiWidth::SING,
            instruction: WRITE_STATUS_REGISTER_CMD,
            address: None,
            dummy: DummyCycles::_0,
        };
        self.qspi.blocking_write(&[value], transaction);
        self.wait_for_write();
    }

    /// Reset read registers into driver's defaults. This makes sure that the
    /// peripheral is configured as expected.
    fn reset_read_register(&mut self) {
        let value = READ_PARAMS_BIT_ODS2
            | READ_PARAMS_BIT_ODS1
            | READ_PARAMS_BIT_ODS0
            | READ_PARAMS_BIT_DC1;
        let transaction = TransferConfig {
            iwidth: QspiWidth::SING,
            awidth: QspiWidth::NONE,
            dwidth: QspiWidth::SING,
            instruction: SET_READ_PARAMETERS_CMD,
            address: None,
            dummy: DummyCycles::_0,
        };
        self.qspi.blocking_write(&[value], transaction);
        self.wait_for_write();
    }

    fn reset(&mut self) {
        self.reset_memory();
        self.reset_status_register();
        self.reset_read_register();
    }
}

impl Flash<'_, Async> {
    pub async fn read_async(&mut self, address: u32, buffer: &mut [u8]) {
        assert!(address + buffer.len() as u32 <= MAX_ADDRESS);

        let transaction = TransferConfig {
            iwidth: QspiWidth::SING,
            awidth: QspiWidth::QUAD,
            dwidth: QspiWidth::QUAD,
            instruction: FAST_READ_QUAD_IO_CMD,
            address: Some(address),
            dummy: DummyCycles::_8,
        };
        self.qspi.read_dma(buffer, transaction).await;
    }

    pub async fn write_async(&mut self, mut address: u32, data: &[u8]) {
        assert!(address <= MAX_ADDRESS);
        assert!(!data.is_empty());
        self.erase_async(address, data.len() as u32).await;
        let mut length = data.len() as u32;
        let mut start_cursor = 0;

        //WRITE_CMD(or PPQ) allows to write up to 256 bytes, which is as much as PAGE_SIZE.
        //Let's divide the data into chunks of page size to write to flash
        loop {
            // Calculate number of bytes between address and end of the page.
            let page_remainder = PAGE_SIZE - (address & (PAGE_SIZE - 1));
            let size = page_remainder.min(length) as usize;
            self.enable_write();
            let transaction = TransferConfig {
                iwidth: QspiWidth::SING,
                awidth: QspiWidth::SING,
                dwidth: QspiWidth::QUAD,
                instruction: WRITE_CMD,
                address: Some(address),
                dummy: DummyCycles::_0,
            };

            self.qspi
                .write_dma(&data[start_cursor..start_cursor + size], transaction)
                .await;
            self.wait_for_write_async(PAGE_WRITE_TIMEOUT).await;
            start_cursor += size;

            // Stop if this was the last needed page.
            if length <= page_remainder {
                break;
            }
            length -= page_remainder;

            // Jump to the next page.
            address += page_remainder;
            address %= MAX_ADDRESS;
        }
    }

    pub async fn erase_async(&mut self, mut address: u32, mut length: u32) {
        assert!(address <= MAX_ADDRESS);
        assert!(length > 0);

        loop {
            // Erase the sector.
            self.enable_write();
            let transaction = TransferConfig {
                iwidth: QspiWidth::SING,
                awidth: QspiWidth::SING,
                dwidth: QspiWidth::NONE,
                instruction: SECTOR_ERASE_CMD,
                address: Some(address),
                dummy: DummyCycles::_0,
            };
            self.qspi.blocking_command(transaction);

            self.wait_for_write_async(SECTOR_ERASE_TIMEOUT).await;

            // Calculate number of bytes between address and end of the sector.
            let sector_remainder = SECTOR_SIZE - (address & (SECTOR_SIZE - 1));

            // Stop if this was the last affected sector.
            if length <= sector_remainder {
                break;
            }
            length -= sector_remainder;

            // Jump to the next sector.
            address += sector_remainder;
            address %= MAX_ADDRESS;
        }
    }

    async fn wait_for_write_async(&mut self, timeout: Duration) {
        let transaction = TransferConfig {
            iwidth: QspiWidth::SING,
            awidth: QspiWidth::NONE,
            dwidth: QspiWidth::SING,
            instruction: READ_STATUS_REGISTER_CMD,
            address: None,
            dummy: DummyCycles::_0,
        };

        self.qspi
            .auto_poll(
                transaction,
                0x10,
                STATUS_BIT_WIP as u32,
                0,
                1,
                MatchMode::AND,
            )
            .with_timeout(timeout)
            .await
            .expect("Flash Timed out waiting for status match")
    }
}