serial.rs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. //! Serial interface loopback test
  2. //!
  3. //! You have to short the TX and RX pins to make this program work
  4. #![deny(unsafe_code)]
  5. #![deny(warnings)]
  6. #![no_main]
  7. #![no_std]
  8. extern crate panic_halt;
  9. use cortex_m::asm;
  10. use nb::block;
  11. use stm32f1xx_hal::{
  12. prelude::*,
  13. pac,
  14. serial::Serial,
  15. };
  16. use cortex_m_rt::entry;
  17. #[entry]
  18. fn main() -> ! {
  19. // Get access to the device specific peripherals from the peripheral access crate
  20. let p = pac::Peripherals::take().unwrap();
  21. // Take ownership over the raw flash and rcc devices and convert them into the corresponding
  22. // HAL structs
  23. let mut flash = p.FLASH.constrain();
  24. let mut rcc = p.RCC.constrain();
  25. // Freeze the configuration of all the clocks in the system and store the frozen frequencies in
  26. // `clocks`
  27. let clocks = rcc.cfgr.freeze(&mut flash.acr);
  28. // Prepare the alternate function I/O registers
  29. let mut afio = p.AFIO.constrain(&mut rcc.apb2);
  30. // Prepare the GPIOB peripheral
  31. let mut gpiob = p.GPIOB.split(&mut rcc.apb2);
  32. // USART1
  33. // let tx = gpioa.pa9.into_alternate_push_pull(&mut gpioa.crh);
  34. // let rx = gpioa.pa10;
  35. // USART1
  36. // let tx = gpiob.pb6.into_alternate_push_pull(&mut gpiob.crl);
  37. // let rx = gpiob.pb7;
  38. // USART2
  39. // let tx = gpioa.pa2.into_alternate_push_pull(&mut gpioa.crl);
  40. // let rx = gpioa.pa3;
  41. // USART3
  42. // Configure pb10 as a push_pull output, this will be the tx pin
  43. let tx = gpiob.pb10.into_alternate_push_pull(&mut gpiob.crh);
  44. // Take ownership over pb11
  45. let rx = gpiob.pb11;
  46. // Set up the usart device. Taks ownership over the USART register and tx/rx pins. The rest of
  47. // the registers are used to enable and configure the device.
  48. let serial = Serial::usart3(
  49. p.USART3,
  50. (tx, rx),
  51. &mut afio.mapr,
  52. 9_600.bps(),
  53. clocks,
  54. &mut rcc.apb1,
  55. );
  56. // Split the serial struct into a receiving and a transmitting part
  57. let (mut tx, mut rx) = serial.split();
  58. let sent = b'X';
  59. // Write `X` and wait until the write is successful
  60. block!(tx.write(sent)).ok();
  61. // Read the byte that was just sent. Blocks until the read is complete
  62. let received = block!(rx.read()).unwrap();
  63. // Since we have connected tx and rx, the byte we sent should be the one we received
  64. assert_eq!(received, sent);
  65. // Trigger a breakpoint to allow us to inspect the values
  66. asm::bkpt();
  67. loop {}
  68. }