From 69cd6203925841f63712f78b50cfac7fd09045a6 Mon Sep 17 00:00:00 2001 From: Luca Date: Thu, 3 Mar 2022 19:08:10 +0100 Subject: [PATCH] Report enter key as pressed when GPIO1 is pulled low --- Cargo.toml | 2 ++ src/main.rs | 64 ++++++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 60 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4bf4e12..7bddbe3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,3 +9,5 @@ embedded-hal = "0.2.7" embedded-time = "0.12.1" panic-halt = "0.2.0" rp-pico = "0.2.0" +usb-device = "0.2.8" +usbd-hid = "0.5.2" diff --git a/src/main.rs b/src/main.rs index 7761ae3..62bcf38 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,7 @@ #![no_std] #![no_main] -use embedded_hal::digital::v2::OutputPin; +use embedded_hal::digital::v2::{InputPin, OutputPin}; use embedded_time::fixed_point::FixedPoint; @@ -9,9 +9,16 @@ use panic_halt as _; use rp_pico::Pins; use rp_pico::entry; -use rp_pico::hal::{Clock, Sio, Watchdog, clocks::init_clocks_and_plls}; +use rp_pico::hal::{Clock, Sio, Watchdog, clocks::init_clocks_and_plls, usb::UsbBus}; use rp_pico::pac::{CorePeripherals, Peripherals}; +use usbd_hid::descriptor::KeyboardReport; +use usbd_hid::descriptor::generator_prelude::*; +use usbd_hid::hid_class::HIDClass; + +use usb_device::bus::UsbBusAllocator; +use usb_device::prelude::*; + #[entry] fn main() -> ! { let mut p = Peripherals::take().unwrap(); @@ -36,13 +43,58 @@ fn main() -> ! { &mut p.RESETS, ); + let gpio1 = pins.gpio1.into_pull_up_input(); let mut led = pins.led.into_push_pull_output(); let mut delay = cortex_m::delay::Delay::new(cp.SYST, clocks.system_clock.freq().integer()); + let usb_bus = UsbBusAllocator::new(UsbBus::new( + p.USBCTRL_REGS, + p.USBCTRL_DPRAM, + clocks.usb_clock, + true, + &mut p.RESETS, + )); + + let mut hid = HIDClass::new(&usb_bus, KeyboardReport::desc(), 127); + + let mut usb_dev = UsbDeviceBuilder::new(&usb_bus, UsbVidPid(0x2342, 0x1337)) + .manufacturer("luj0ga") + .product("pico-test") + .serial_number("0.1.0") + .device_class(3) // HID + .build(); + + let mut counter = 0; loop { - led.set_high().unwrap(); - delay.delay_ms(500); - led.set_low().unwrap(); - delay.delay_ms(500); + usb_dev.poll(&mut [&mut hid]); + + if let Ok(key_down) = gpio1.is_low() { + let report = if key_down { + KeyboardReport { + modifier: 0, + reserved: 0, + leds: 0, + keycodes: [0x28, 0, 0, 0, 0, 0], + } + } else { + KeyboardReport { + modifier: 0, + reserved: 0, + leds: 0, + keycodes: [0, 0, 0, 0, 0, 0], + } + }; + + hid.push_input(&report).ok(); + } + + if counter == 0 { + led.set_high().unwrap(); + } else if counter == 100 { + led.set_low().unwrap(); + } + + delay.delay_ms(5); + counter = (counter + 1) % 200; } }