usb_serial.rs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //! CDC-ACM serial port example using polling in a busy loop.
  2. //! Target board: Blue Pill
  3. #![no_std]
  4. #![no_main]
  5. extern crate panic_semihosting;
  6. use cortex_m::asm::delay;
  7. use cortex_m_rt::entry;
  8. use embedded_hal::digital::v2::OutputPin;
  9. use stm32f1xx_hal::usb::{Peripheral, UsbBus};
  10. use stm32f1xx_hal::{prelude::*, stm32};
  11. use usb_device::prelude::*;
  12. use usbd_serial::{SerialPort, USB_CLASS_CDC};
  13. #[entry]
  14. fn main() -> ! {
  15. let dp = pac::Peripherals::take().unwrap();
  16. let mut flash = dp.FLASH.constrain();
  17. let mut rcc = dp.RCC.constrain();
  18. let clocks = rcc
  19. .cfgr
  20. .use_hse(8.mhz())
  21. .sysclk(48.mhz())
  22. .pclk1(24.mhz())
  23. .freeze(&mut flash.acr);
  24. assert!(clocks.usbclk_valid());
  25. // Configure the on-board LED (PC13, green)
  26. let mut gpioc = dp.GPIOC.split(&mut rcc.apb2);
  27. let mut led = gpioc.pc13.into_push_pull_output(&mut gpioc.crh);
  28. led.set_high(); // Turn off
  29. let mut gpioa = dp.GPIOA.split(&mut rcc.apb2);
  30. // BluePill board has a pull-up resistor on the D+ line.
  31. // Pull the D+ pin down to send a RESET condition to the USB bus.
  32. // This forced reset is needed only for development, without it host
  33. // will not reset your device when you upload new firmware.
  34. let mut usb_dp = gpioa.pa12.into_push_pull_output(&mut gpioa.crh);
  35. usb_dp.set_low();
  36. delay(clocks.sysclk().0 / 100);
  37. let usb = Peripheral {
  38. usb: dp.USB,
  39. pin_dm: gpioa.pa11,
  40. pin_dp: usb_dp.into_floating_input(&mut gpioa.crh),
  41. };
  42. let usb_bus = UsbBus::new(usb);
  43. let mut serial = SerialPort::new(&usb_bus);
  44. let mut usb_dev = UsbDeviceBuilder::new(&usb_bus, UsbVidPid(0x16c0, 0x27dd))
  45. .manufacturer("Fake company")
  46. .product("Serial port")
  47. .serial_number("TEST")
  48. .device_class(USB_CLASS_CDC)
  49. .build();
  50. loop {
  51. if !usb_dev.poll(&mut [&mut serial]) {
  52. continue;
  53. }
  54. let mut buf = [0u8; 64];
  55. match serial.read(&mut buf) {
  56. Ok(count) if count > 0 => {
  57. led.set_low(); // Turn on
  58. // Echo back in upper case
  59. for c in buf[0..count].iter_mut() {
  60. if 0x61 <= *c && *c <= 0x7a {
  61. *c &= !0x20;
  62. }
  63. }
  64. let mut write_offset = 0;
  65. while write_offset < count {
  66. match serial.write(&buf[write_offset..count]) {
  67. Ok(len) if len > 0 => {
  68. write_offset += len;
  69. }
  70. _ => {}
  71. }
  72. }
  73. }
  74. _ => {}
  75. }
  76. led.set_high(); // Turn off
  77. }
  78. }