|
| 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 | + block, delay::DelayFromCountDownTimer, gpio::gpioa::PA5, gpio::gpioa::PA6, gpio::gpioa::PA7, |
| 10 | + gpio::Alternate, gpio::AF5, prelude::*, rcc::Config, spi, stm32::Peripherals, timer::Timer, |
| 11 | +}; |
| 12 | + |
| 13 | +use cortex_m_rt::entry; |
| 14 | +use log::info; |
| 15 | +use stm32g4xx_hal as hal; |
| 16 | + |
| 17 | +#[macro_use] |
| 18 | +mod utils; |
| 19 | + |
| 20 | +#[entry] |
| 21 | +fn main() -> ! { |
| 22 | + utils::logger::init(); |
| 23 | + |
| 24 | + let dp = Peripherals::take().unwrap(); |
| 25 | + let rcc = dp.RCC.constrain(); |
| 26 | + let mut rcc = rcc.freeze(Config::hsi()); |
| 27 | + let timer2 = Timer::new(dp.TIM2, &rcc.clocks); |
| 28 | + let mut delay_tim2 = DelayFromCountDownTimer::new(timer2.start_count_down(100.ms())); |
| 29 | + |
| 30 | + let gpioa = dp.GPIOA.split(&mut rcc); |
| 31 | + let sclk: PA5<Alternate<AF5>> = gpioa.pa5.into_alternate(); |
| 32 | + let miso: PA6<Alternate<AF5>> = gpioa.pa6.into_alternate(); |
| 33 | + let mosi: PA7<Alternate<AF5>> = gpioa.pa7.into_alternate(); |
| 34 | + |
| 35 | + let mut spi = dp |
| 36 | + .SPI1 |
| 37 | + .spi((sclk, miso, mosi), spi::MODE_0, 400.khz(), &mut rcc); |
| 38 | + let mut cs = gpioa.pa8.into_push_pull_output(); |
| 39 | + cs.set_high().unwrap(); |
| 40 | + |
| 41 | + // "Hello world!" |
| 42 | + let message: [char; 12] = ['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']; |
| 43 | + let mut received_byte: u8; |
| 44 | + |
| 45 | + loop { |
| 46 | + for byte in message.iter() { |
| 47 | + cs.set_low().unwrap(); |
| 48 | + spi.send(*byte as u8).unwrap(); |
| 49 | + received_byte = block!(spi.read()).unwrap(); |
| 50 | + cs.set_high().unwrap(); |
| 51 | + |
| 52 | + info!("{}", received_byte as char); |
| 53 | + } |
| 54 | + delay_tim2.delay_ms(1000_u16); |
| 55 | + } |
| 56 | +} |
0 commit comments