Skip to content

Commit 6dfc859

Browse files
committed
Add minimal spi example
1 parent b76f038 commit 6dfc859

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,7 @@ required-features = ["rt", "stm32f303xc"]
8686
[[example]]
8787
name = "usb_serial"
8888
required-features = ["rt", "stm32f303xc", "stm32-usbd"]
89+
90+
[[example]]
91+
name = "spi"
92+
required-features = ["stm32f303"]

examples/spi.rs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
//! Example of configuring spi.
2+
//! Target board: STM32F3DISCOVERY
3+
#![no_std]
4+
#![no_main]
5+
6+
extern crate panic_semihosting;
7+
8+
use stm32f3xx_hal as hal;
9+
10+
use cortex_m_rt::entry;
11+
12+
use hal::prelude::*;
13+
use hal::spi::{Mode, Phase, Polarity, Spi};
14+
use hal::stm32;
15+
16+
#[entry]
17+
fn main() -> ! {
18+
let dp = stm32::Peripherals::take().unwrap();
19+
20+
let mut flash = dp.FLASH.constrain();
21+
let mut rcc = dp.RCC.constrain();
22+
let mut gpioa = dp.GPIOA.split(&mut rcc.ahb);
23+
24+
let clocks = rcc
25+
.cfgr
26+
.use_hse(8.mhz())
27+
.sysclk(48.mhz())
28+
.pclk1(24.mhz())
29+
.freeze(&mut flash.acr);
30+
31+
// Configure pins for SPI
32+
let sck = gpioa.pa5.into_af5(&mut gpioa.moder, &mut gpioa.afrl);
33+
let miso = gpioa.pa6.into_af5(&mut gpioa.moder, &mut gpioa.afrl);
34+
let mosi = gpioa.pa7.into_af5(&mut gpioa.moder, &mut gpioa.afrl);
35+
36+
let spi_mode = Mode {
37+
polarity: Polarity::IdleLow,
38+
phase: Phase::CaptureOnFirstTransition,
39+
};
40+
41+
let mut spi = Spi::spi1(
42+
dp.SPI1,
43+
(sck, miso, mosi),
44+
spi_mode,
45+
3.mhz(),
46+
clocks,
47+
&mut rcc.apb2,
48+
);
49+
50+
// Create an `u8` array, which can be transfered via SPI.
51+
let msg_send: [u8; 8] = [0xD, 0xE, 0xA, 0xD, 0xB, 0xE, 0xE, 0xF];
52+
// Clone the array, as it would be mutually shared in `transfer` while simultaniously would be
53+
// immutable shared in `assert_eq`.
54+
let mut msg_sending = msg_send.clone();
55+
// Transfer the content of the array via SPI and receive it's output.
56+
// When MOSI and MISO pins are connected together, `msg_received` should receive the content.
57+
// from `msg_sending`
58+
let msg_received = spi.transfer(&mut msg_sending).unwrap();
59+
60+
// Check, if msg_send and msg_received are identical.
61+
// This succeeds, when master and slave of the SPI are connected.
62+
assert_eq!(msg_send, msg_received);
63+
64+
loop {}
65+
}

0 commit comments

Comments
 (0)