aboutsummaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rw-r--r--examples/stm32h7b0/.cargo/config.toml8
-rw-r--r--examples/stm32h7b0/Cargo.toml74
-rw-r--r--examples/stm32h7b0/build.rs35
-rw-r--r--examples/stm32h7b0/memory.x5
-rw-r--r--examples/stm32h7b0/src/bin/ospi_memory_mapped.rs433
5 files changed, 555 insertions, 0 deletions
diff --git a/examples/stm32h7b0/.cargo/config.toml b/examples/stm32h7b0/.cargo/config.toml
new file mode 100644
index 000000000..870849a27
--- /dev/null
+++ b/examples/stm32h7b0/.cargo/config.toml
@@ -0,0 +1,8 @@
1[target.thumbv7em-none-eabihf]
2runner = 'probe-rs run --chip STM32H7B0VBTx'
3
4[build]
5target = "thumbv7em-none-eabihf" # Cortex-M4F and Cortex-M7F (with FPU)
6
7[env]
8DEFMT_LOG = "trace"
diff --git a/examples/stm32h7b0/Cargo.toml b/examples/stm32h7b0/Cargo.toml
new file mode 100644
index 000000000..02c620443
--- /dev/null
+++ b/examples/stm32h7b0/Cargo.toml
@@ -0,0 +1,74 @@
1[package]
2edition = "2021"
3name = "embassy-stm32h7b0-examples"
4version = "0.1.0"
5license = "MIT OR Apache-2.0"
6
7[dependencies]
8embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32h7b0vb", "time-driver-tim2", "exti", "memory-x", "unstable-pac", "chrono"] }
9embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] }
10embassy-embedded-hal = { version = "0.2.0", path = "../../embassy-embedded-hal" }
11embassy-executor = { version = "0.6.1", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] }
12embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] }
13embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", "proto-ipv6", "dns"] }
14embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] }
15embassy-futures = { version = "0.1.0", path = "../../embassy-futures" }
16
17defmt = "0.3"
18defmt-rtt = "0.4"
19
20cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] }
21cortex-m-rt = "0.7.0"
22embedded-hal = "0.2.6"
23embedded-hal-1 = { package = "embedded-hal", version = "1.0" }
24embedded-hal-async = { version = "1.0" }
25embedded-nal-async = "0.8.0"
26embedded-io-async = { version = "0.6.1" }
27panic-probe = { version = "0.3", features = ["print-defmt"] }
28heapless = { version = "0.8", default-features = false }
29rand_core = "0.6.3"
30critical-section = "1.1"
31micromath = "2.0.0"
32stm32-fmc = "0.3.0"
33embedded-storage = "0.3.1"
34static_cell = "2"
35chrono = { version = "^0.4", default-features = false }
36grounded = "0.2.0"
37
38# cargo build/run
39[profile.dev]
40codegen-units = 1
41debug = 2
42debug-assertions = true # <-
43incremental = false
44opt-level = 3 # <-
45overflow-checks = true # <-
46
47# cargo test
48[profile.test]
49codegen-units = 1
50debug = 2
51debug-assertions = true # <-
52incremental = false
53opt-level = 3 # <-
54overflow-checks = true # <-
55
56# cargo build/run --release
57[profile.release]
58codegen-units = 1
59debug = 2
60debug-assertions = false # <-
61incremental = false
62lto = 'fat'
63opt-level = 3 # <-
64overflow-checks = false # <-
65
66# cargo test --release
67[profile.bench]
68codegen-units = 1
69debug = 2
70debug-assertions = false # <-
71incremental = false
72lto = 'fat'
73opt-level = 3 # <-
74overflow-checks = false # <-
diff --git a/examples/stm32h7b0/build.rs b/examples/stm32h7b0/build.rs
new file mode 100644
index 000000000..30691aa97
--- /dev/null
+++ b/examples/stm32h7b0/build.rs
@@ -0,0 +1,35 @@
1//! This build script copies the `memory.x` file from the crate root into
2//! a directory where the linker can always find it at build time.
3//! For many projects this is optional, as the linker always searches the
4//! project root directory -- wherever `Cargo.toml` is. However, if you
5//! are using a workspace or have a more complicated build setup, this
6//! build script becomes required. Additionally, by requesting that
7//! Cargo re-run the build script whenever `memory.x` is changed,
8//! updating `memory.x` ensures a rebuild of the application with the
9//! new memory settings.
10
11use std::env;
12use std::fs::File;
13use std::io::Write;
14use std::path::PathBuf;
15
16fn main() {
17 // Put `memory.x` in our output directory and ensure it's
18 // on the linker search path.
19 let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
20 File::create(out.join("memory.x"))
21 .unwrap()
22 .write_all(include_bytes!("memory.x"))
23 .unwrap();
24 println!("cargo:rustc-link-search={}", out.display());
25
26 // By default, Cargo will re-run a build script whenever
27 // any file in the project changes. By specifying `memory.x`
28 // here, we ensure the build script is only re-run when
29 // `memory.x` is changed.
30 println!("cargo:rerun-if-changed=memory.x");
31
32 println!("cargo:rustc-link-arg-bins=--nmagic");
33 println!("cargo:rustc-link-arg-bins=-Tlink.x");
34 println!("cargo:rustc-link-arg-bins=-Tdefmt.x");
35}
diff --git a/examples/stm32h7b0/memory.x b/examples/stm32h7b0/memory.x
new file mode 100644
index 000000000..6eb1bb7c1
--- /dev/null
+++ b/examples/stm32h7b0/memory.x
@@ -0,0 +1,5 @@
1MEMORY
2{
3 FLASH : ORIGIN = 0x08000000, LENGTH = 128K /* BANK_1 */
4 RAM : ORIGIN = 0x24000000, LENGTH = 512K /* SRAM */
5} \ No newline at end of file
diff --git a/examples/stm32h7b0/src/bin/ospi_memory_mapped.rs b/examples/stm32h7b0/src/bin/ospi_memory_mapped.rs
new file mode 100644
index 000000000..9c397e507
--- /dev/null
+++ b/examples/stm32h7b0/src/bin/ospi_memory_mapped.rs
@@ -0,0 +1,433 @@
1#![no_main]
2#![no_std]
3
4// Tested on weact stm32h7b0 board + w25q64 spi flash
5
6use defmt::info;
7use embassy_executor::Spawner;
8use embassy_stm32::gpio::{Level, Output, Speed};
9use embassy_stm32::mode::Blocking;
10use embassy_stm32::ospi::{
11 AddressSize, ChipSelectHighTime, DummyCycles, FIFOThresholdLevel, Instance, MemorySize, MemoryType, Ospi,
12 OspiWidth, TransferConfig, WrapSize,
13};
14use embassy_stm32::time::Hertz;
15use embassy_stm32::Config;
16use embassy_time::Timer;
17use {defmt_rtt as _, panic_probe as _};
18
19#[embassy_executor::main]
20async fn main(_spawner: Spawner) {
21 // RCC config
22 let mut config = Config::default();
23 info!("START");
24 {
25 use embassy_stm32::rcc::*;
26 config.rcc.hsi = Some(HSIPrescaler::DIV1);
27 config.rcc.csi = true;
28 // Needed for USB
29 config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true });
30 // External oscillator 25MHZ
31 config.rcc.hse = Some(Hse {
32 freq: Hertz(25_000_000),
33 mode: HseMode::Oscillator,
34 });
35 config.rcc.pll1 = Some(Pll {
36 source: PllSource::HSE,
37 prediv: PllPreDiv::DIV5,
38 mul: PllMul::MUL112,
39 divp: Some(PllDiv::DIV2),
40 divq: Some(PllDiv::DIV2),
41 divr: Some(PllDiv::DIV2),
42 });
43 config.rcc.sys = Sysclk::PLL1_P;
44 config.rcc.ahb_pre = AHBPrescaler::DIV2;
45 config.rcc.apb1_pre = APBPrescaler::DIV2;
46 config.rcc.apb2_pre = APBPrescaler::DIV2;
47 config.rcc.apb3_pre = APBPrescaler::DIV2;
48 config.rcc.apb4_pre = APBPrescaler::DIV2;
49 config.rcc.voltage_scale = VoltageScale::Scale0;
50 }
51
52 // Initialize peripherals
53 let p = embassy_stm32::init(config);
54
55 let qspi_config = embassy_stm32::ospi::Config {
56 fifo_threshold: FIFOThresholdLevel::_16Bytes,
57 memory_type: MemoryType::Micron,
58 device_size: MemorySize::_8MiB,
59 chip_select_high_time: ChipSelectHighTime::_1Cycle,
60 free_running_clock: false,
61 clock_mode: false,
62 wrap_size: WrapSize::None,
63 clock_prescaler: 4,
64 sample_shifting: true,
65 delay_hold_quarter_cycle: false,
66 chip_select_boundary: 0,
67 delay_block_bypass: true,
68 max_transfer: 0,
69 refresh: 0,
70 };
71 let ospi = embassy_stm32::ospi::Ospi::new_blocking_quadspi(
72 p.OCTOSPI1,
73 p.PB2,
74 p.PD11,
75 p.PD12,
76 p.PE2,
77 p.PD13,
78 p.PB6,
79 qspi_config,
80 );
81
82 let mut flash = FlashMemory::new(ospi).await;
83
84 let flash_id = flash.read_id();
85 info!("FLASH ID: {=[u8]:x}", flash_id);
86 let mut wr_buf = [0u8; 8];
87 for i in 0..8 {
88 wr_buf[i] = i as u8;
89 }
90 let mut rd_buf = [0u8; 8];
91 flash.erase_sector(0).await;
92 flash.write_memory(0, &wr_buf, true).await;
93 flash.read_memory(0, &mut rd_buf, true);
94 info!("WRITE BUF: {=[u8]:#X}", wr_buf);
95 info!("READ BUF: {=[u8]:#X}", rd_buf);
96 flash.enable_mm().await;
97 info!("Enabled memory mapped mode");
98
99 let first_u32 = unsafe { *(0x90000000 as *const u32) };
100 assert_eq!(first_u32, 0x03020100);
101
102 let second_u32 = unsafe { *(0x90000004 as *const u32) };
103 assert_eq!(second_u32, 0x07060504);
104 flash.disable_mm().await;
105
106 info!("DONE");
107 // Output pin PE3
108 let mut led = Output::new(p.PE3, Level::Low, Speed::Low);
109
110 loop {
111 led.toggle();
112 Timer::after_millis(1000).await;
113 }
114}
115
116const MEMORY_PAGE_SIZE: usize = 8;
117
118const CMD_QUAD_READ: u8 = 0x6B;
119
120const CMD_QUAD_WRITE_PG: u8 = 0x32;
121
122const CMD_READ_ID: u8 = 0x9F;
123
124const CMD_ENABLE_RESET: u8 = 0x66;
125const CMD_RESET: u8 = 0x99;
126
127const CMD_WRITE_ENABLE: u8 = 0x06;
128
129const CMD_CHIP_ERASE: u8 = 0xC7;
130const CMD_SECTOR_ERASE: u8 = 0x20;
131const CMD_BLOCK_ERASE_32K: u8 = 0x52;
132const CMD_BLOCK_ERASE_64K: u8 = 0xD8;
133
134const CMD_READ_SR: u8 = 0x05;
135const CMD_READ_CR: u8 = 0x35;
136
137const CMD_WRITE_SR: u8 = 0x01;
138const CMD_WRITE_CR: u8 = 0x31;
139
140/// Implementation of access to flash chip.
141/// Chip commands are hardcoded as it depends on used chip.
142/// This implementation is using chip GD25Q64C from Giga Device
143pub struct FlashMemory<I: Instance> {
144 ospi: Ospi<'static, I, Blocking>,
145}
146
147impl<I: Instance> FlashMemory<I> {
148 pub async fn new(ospi: Ospi<'static, I, Blocking>) -> Self {
149 let mut memory = Self { ospi };
150
151 memory.reset_memory().await;
152 memory.enable_quad();
153 memory
154 }
155
156 async fn qpi_mode(&mut self) {
157 // Enter qpi mode
158 self.exec_command(0x38).await;
159
160 // Set read param
161 let transaction = TransferConfig {
162 iwidth: OspiWidth::QUAD,
163 dwidth: OspiWidth::QUAD,
164 instruction: Some(0xC0),
165 ..Default::default()
166 };
167 self.enable_write().await;
168 self.ospi.blocking_write(&[0x30_u8], transaction).unwrap();
169 self.wait_write_finish();
170 }
171
172 pub async fn disable_mm(&mut self) {
173 self.ospi.disable_memory_mapped_mode();
174 }
175
176 pub async fn enable_mm(&mut self) {
177 self.qpi_mode().await;
178
179 let read_config = TransferConfig {
180 iwidth: OspiWidth::QUAD,
181 isize: AddressSize::_8Bit,
182 adwidth: OspiWidth::QUAD,
183 adsize: AddressSize::_24bit,
184 dwidth: OspiWidth::QUAD,
185 instruction: Some(0x0B), // Fast read in QPI mode
186 dummy: DummyCycles::_8,
187 ..Default::default()
188 };
189
190 let write_config = TransferConfig {
191 iwidth: OspiWidth::SING,
192 isize: AddressSize::_8Bit,
193 adwidth: OspiWidth::SING,
194 adsize: AddressSize::_24bit,
195 dwidth: OspiWidth::QUAD,
196 instruction: Some(0x32), // Write config
197 dummy: DummyCycles::_0,
198 ..Default::default()
199 };
200 self.ospi.enable_memory_mapped_mode(read_config, write_config).unwrap();
201 }
202
203 fn enable_quad(&mut self) {
204 let cr = self.read_cr();
205 // info!("Read cr: {:x}", cr);
206 self.write_cr(cr | 0x02);
207 // info!("Read cr after writing: {:x}", cr);
208 }
209
210 pub fn disable_quad(&mut self) {
211 let cr = self.read_cr();
212 self.write_cr(cr & (!(0x02)));
213 }
214
215 async fn exec_command_4(&mut self, cmd: u8) {
216 let transaction = TransferConfig {
217 iwidth: OspiWidth::QUAD,
218 adwidth: OspiWidth::NONE,
219 // adsize: AddressSize::_24bit,
220 dwidth: OspiWidth::NONE,
221 instruction: Some(cmd as u32),
222 address: None,
223 dummy: DummyCycles::_0,
224 ..Default::default()
225 };
226 self.ospi.command(&transaction).await.unwrap();
227 }
228
229 async fn exec_command(&mut self, cmd: u8) {
230 let transaction = TransferConfig {
231 iwidth: OspiWidth::SING,
232 adwidth: OspiWidth::NONE,
233 // adsize: AddressSize::_24bit,
234 dwidth: OspiWidth::NONE,
235 instruction: Some(cmd as u32),
236 address: None,
237 dummy: DummyCycles::_0,
238 ..Default::default()
239 };
240 // info!("Excuting command: {:x}", transaction.instruction);
241 self.ospi.command(&transaction).await.unwrap();
242 }
243
244 pub async fn reset_memory(&mut self) {
245 self.exec_command_4(CMD_ENABLE_RESET).await;
246 self.exec_command_4(CMD_RESET).await;
247 self.exec_command(CMD_ENABLE_RESET).await;
248 self.exec_command(CMD_RESET).await;
249 self.wait_write_finish();
250 }
251
252 pub async fn enable_write(&mut self) {
253 self.exec_command(CMD_WRITE_ENABLE).await;
254 }
255
256 pub fn read_id(&mut self) -> [u8; 3] {
257 let mut buffer = [0; 3];
258 let transaction: TransferConfig = TransferConfig {
259 iwidth: OspiWidth::SING,
260 isize: AddressSize::_8Bit,
261 adwidth: OspiWidth::NONE,
262 // adsize: AddressSize::_24bit,
263 dwidth: OspiWidth::SING,
264 instruction: Some(CMD_READ_ID as u32),
265 ..Default::default()
266 };
267 // info!("Reading id: 0x{:X}", transaction.instruction);
268 self.ospi.blocking_read(&mut buffer, transaction).unwrap();
269 buffer
270 }
271
272 pub fn read_id_4(&mut self) -> [u8; 3] {
273 let mut buffer = [0; 3];
274 let transaction: TransferConfig = TransferConfig {
275 iwidth: OspiWidth::SING,
276 isize: AddressSize::_8Bit,
277 adwidth: OspiWidth::NONE,
278 dwidth: OspiWidth::QUAD,
279 instruction: Some(CMD_READ_ID as u32),
280 ..Default::default()
281 };
282 info!("Reading id: 0x{:X}", transaction.instruction);
283 self.ospi.blocking_read(&mut buffer, transaction).unwrap();
284 buffer
285 }
286
287 pub fn read_memory(&mut self, addr: u32, buffer: &mut [u8], use_dma: bool) {
288 let transaction = TransferConfig {
289 iwidth: OspiWidth::SING,
290 adwidth: OspiWidth::SING,
291 adsize: AddressSize::_24bit,
292 dwidth: OspiWidth::QUAD,
293 instruction: Some(CMD_QUAD_READ as u32),
294 address: Some(addr),
295 dummy: DummyCycles::_8,
296 ..Default::default()
297 };
298 if use_dma {
299 self.ospi.blocking_read(buffer, transaction).unwrap();
300 } else {
301 self.ospi.blocking_read(buffer, transaction).unwrap();
302 }
303 }
304
305 fn wait_write_finish(&mut self) {
306 while (self.read_sr() & 0x01) != 0 {}
307 }
308
309 async fn perform_erase(&mut self, addr: u32, cmd: u8) {
310 let transaction = TransferConfig {
311 iwidth: OspiWidth::SING,
312 adwidth: OspiWidth::SING,
313 adsize: AddressSize::_24bit,
314 dwidth: OspiWidth::NONE,
315 instruction: Some(cmd as u32),
316 address: Some(addr),
317 dummy: DummyCycles::_0,
318 ..Default::default()
319 };
320 self.enable_write().await;
321 self.ospi.command(&transaction).await.unwrap();
322 self.wait_write_finish();
323 }
324
325 pub async fn erase_sector(&mut self, addr: u32) {
326 self.perform_erase(addr, CMD_SECTOR_ERASE).await;
327 }
328
329 pub async fn erase_block_32k(&mut self, addr: u32) {
330 self.perform_erase(addr, CMD_BLOCK_ERASE_32K).await;
331 }
332
333 pub async fn erase_block_64k(&mut self, addr: u32) {
334 self.perform_erase(addr, CMD_BLOCK_ERASE_64K).await;
335 }
336
337 pub async fn erase_chip(&mut self) {
338 self.exec_command(CMD_CHIP_ERASE).await;
339 }
340
341 async fn write_page(&mut self, addr: u32, buffer: &[u8], len: usize, use_dma: bool) {
342 assert!(
343 (len as u32 + (addr & 0x000000ff)) <= MEMORY_PAGE_SIZE as u32,
344 "write_page(): page write length exceeds page boundary (len = {}, addr = {:X}",
345 len,
346 addr
347 );
348
349 let transaction = TransferConfig {
350 iwidth: OspiWidth::SING,
351 adsize: AddressSize::_24bit,
352 adwidth: OspiWidth::SING,
353 dwidth: OspiWidth::QUAD,
354 instruction: Some(CMD_QUAD_WRITE_PG as u32),
355 address: Some(addr),
356 dummy: DummyCycles::_0,
357 ..Default::default()
358 };
359 self.enable_write().await;
360 if use_dma {
361 self.ospi.blocking_write(buffer, transaction).unwrap();
362 } else {
363 self.ospi.blocking_write(buffer, transaction).unwrap();
364 }
365 self.wait_write_finish();
366 }
367
368 pub async fn write_memory(&mut self, addr: u32, buffer: &[u8], use_dma: bool) {
369 let mut left = buffer.len();
370 let mut place = addr;
371 let mut chunk_start = 0;
372
373 while left > 0 {
374 let max_chunk_size = MEMORY_PAGE_SIZE - (place & 0x000000ff) as usize;
375 let chunk_size = if left >= max_chunk_size { max_chunk_size } else { left };
376 let chunk = &buffer[chunk_start..(chunk_start + chunk_size)];
377 self.write_page(place, chunk, chunk_size, use_dma).await;
378 place += chunk_size as u32;
379 left -= chunk_size;
380 chunk_start += chunk_size;
381 }
382 }
383
384 fn read_register(&mut self, cmd: u8) -> u8 {
385 let mut buffer = [0; 1];
386 let transaction: TransferConfig = TransferConfig {
387 iwidth: OspiWidth::SING,
388 isize: AddressSize::_8Bit,
389 adwidth: OspiWidth::NONE,
390 adsize: AddressSize::_24bit,
391 dwidth: OspiWidth::SING,
392 instruction: Some(cmd as u32),
393 address: None,
394 dummy: DummyCycles::_0,
395 ..Default::default()
396 };
397 self.ospi.blocking_read(&mut buffer, transaction).unwrap();
398 // info!("Read w25q64 register: 0x{:x}", buffer[0]);
399 buffer[0]
400 }
401
402 fn write_register(&mut self, cmd: u8, value: u8) {
403 let buffer = [value; 1];
404 let transaction: TransferConfig = TransferConfig {
405 iwidth: OspiWidth::SING,
406 isize: AddressSize::_8Bit,
407 instruction: Some(cmd as u32),
408 adsize: AddressSize::_24bit,
409 adwidth: OspiWidth::NONE,
410 dwidth: OspiWidth::SING,
411 address: None,
412 dummy: DummyCycles::_0,
413 ..Default::default()
414 };
415 self.ospi.blocking_write(&buffer, transaction).unwrap();
416 }
417
418 pub fn read_sr(&mut self) -> u8 {
419 self.read_register(CMD_READ_SR)
420 }
421
422 pub fn read_cr(&mut self) -> u8 {
423 self.read_register(CMD_READ_CR)
424 }
425
426 pub fn write_sr(&mut self, value: u8) {
427 self.write_register(CMD_WRITE_SR, value);
428 }
429
430 pub fn write_cr(&mut self, value: u8) {
431 self.write_register(CMD_WRITE_CR, value);
432 }
433}