|
| 1 | +// This example is to test the SPI without any external devices. |
| 2 | +// It puts "Hello world!" on the mosi-line and logs whatever is received on the miso-line to the info level. |
| 3 | +// The idea is that you should connect miso and mosi, so you will also receive "Hello world!". |
| 4 | + |
| 5 | +#![no_main] |
| 6 | +#![no_std] |
| 7 | + |
| 8 | +use crate::hal::{ |
| 9 | + delay::DelayFromCountDownTimer, |
| 10 | + prelude::*, |
| 11 | + pwr::PwrExt, |
| 12 | + rcc::Config, |
| 13 | + spi, |
| 14 | + stm32::Peripherals, |
| 15 | + time::{ExtU32, RateExtU32}, |
| 16 | + timer::Timer, |
| 17 | +}; |
| 18 | + |
| 19 | +use cortex_m_rt::entry; |
| 20 | +use embedded_hal_one::spi::SpiBus; |
| 21 | +use stm32g4xx_hal as hal; |
| 22 | + |
| 23 | +#[macro_use] |
| 24 | +mod utils; |
| 25 | +use utils::logger::info; |
| 26 | + |
| 27 | +#[entry] |
| 28 | +fn main() -> ! { |
| 29 | + utils::logger::init(); |
| 30 | + info!("Logger init"); |
| 31 | + |
| 32 | + let dp = Peripherals::take().unwrap(); |
| 33 | + let rcc = dp.RCC.constrain(); |
| 34 | + let pwr = dp.PWR.constrain().freeze(); |
| 35 | + let mut rcc = rcc.freeze(Config::hsi(), pwr); |
| 36 | + let timer2 = Timer::new(dp.TIM2, &rcc.clocks); |
| 37 | + let mut delay_tim2 = DelayFromCountDownTimer::new(timer2.start_count_down(100.millis())); |
| 38 | + |
| 39 | + // let gpioa = dp.GPIOA.split(&mut rcc); |
| 40 | + let gpioa = dp.GPIOA.split(&mut rcc); |
| 41 | + let sclk = gpioa.pa5.into_alternate(); |
| 42 | + let miso = gpioa.pa6.into_alternate(); |
| 43 | + let mosi = gpioa.pa7.into_alternate(); |
| 44 | + |
| 45 | + let mut spi = dp |
| 46 | + .SPI1 |
| 47 | + .spi((sclk, miso, mosi), spi::MODE_0, 400.kHz(), &mut rcc); |
| 48 | + let mut cs = gpioa.pa8.into_push_pull_output(); |
| 49 | + cs.set_high().unwrap(); |
| 50 | + |
| 51 | + // "Hello world!" |
| 52 | + const MESSAGE: &[u8] = "Hello world!".as_bytes(); |
| 53 | + let received = &mut [0u8; MESSAGE.len()]; |
| 54 | + |
| 55 | + cs.set_low().unwrap(); |
| 56 | + SpiBus::transfer(&mut spi, received, MESSAGE).unwrap(); |
| 57 | + spi.flush().unwrap(); |
| 58 | + cs.set_high().unwrap(); |
| 59 | + |
| 60 | + info!("Received {:?}", core::str::from_utf8(received).ok()); |
| 61 | + delay_tim2.delay_ms(10_u16); |
| 62 | + |
| 63 | + cs.set_low().unwrap(); |
| 64 | + embedded_hal::blocking::spi::Write::write(&mut spi, received).unwrap(); |
| 65 | + cs.set_high().unwrap(); |
| 66 | + |
| 67 | + // info!("{:?}", core::str::from_utf8(received).ok()); |
| 68 | + loop { |
| 69 | + cortex_m::asm::nop(); |
| 70 | + } |
| 71 | +} |
0 commit comments