-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy patharduino_keyboard.rs
204 lines (179 loc) · 5.6 KB
/
arduino_keyboard.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
//! A "Hello World" example that can be run on an Arduino Leonardo.
//!
//! # Usage
//!
//! 1. (Optional) Connect a pushbutton switch to the D2 pin of the Leonardo, and
//! connect the other pin of the switch to GND.
//!
//! 2. Connect the Leonardo to the computer with a USB cable.
//!
//! 3. Make sure [Ravedude](https://github.com/Rahix/avr-hal/tree/main/ravedude)
//! is installed. Then "run" the example to deploy it to the Arduino:
//!
//! ```
//! cargo run --release --example arduino_keyboard
//! ```
//!
//! 4. Open Notepad (or whatever editor or text input of your choosing). Press
//! the button (or if you are not using one, short D2 to GND with a jumper). You
//! should see it type "Hello World"
#![no_std]
#![cfg_attr(not(test), no_main)]
#![feature(lang_items)]
#![feature(abi_avr_interrupt)]
#![deny(unsafe_op_in_unsafe_fn)]
mod std_stub;
use arduino_hal::{
entry,
pac::PLL,
pins,
port::{
mode::{Input, Output, PullUp},
Pin,
},
Peripherals,
};
use atmega_usbd::{SuspendNotifier, UsbBus};
use avr_device::{asm::sleep, interrupt};
use usb_device::{
class_prelude::UsbBusAllocator,
device::{UsbDevice, UsbDeviceBuilder, UsbVidPid},
};
use usbd_hid::{
descriptor::{KeyboardReport, SerializedDescriptor},
hid_class::HIDClass,
};
const PAYLOAD: &[u8] = b"Hello World";
#[entry]
fn main() -> ! {
let dp = Peripherals::take().unwrap();
let pins = pins!(dp);
let pll = dp.PLL;
let usb = dp.USB_DEVICE;
let status = pins.d13.into_output();
let trigger = pins.d2.into_pull_up_input();
// Configure PLL interface
// prescale 16MHz crystal -> 8MHz
pll.pllcsr.write(|w| w.pindiv().set_bit());
// 96MHz PLL output; /1.5 for 64MHz timers, /2 for 48MHz USB
pll.pllfrq
.write(|w| w.pdiv().mhz96().plltm().factor_15().pllusb().set_bit());
// Enable PLL
pll.pllcsr.modify(|_, w| w.plle().set_bit());
// Check PLL lock
while pll.pllcsr.read().plock().bit_is_clear() {}
let usb_bus = unsafe {
static mut USB_BUS: Option<UsbBusAllocator<UsbBus<PLL>>> = None;
&*USB_BUS.insert(UsbBus::with_suspend_notifier(usb, pll))
};
let hid_class = HIDClass::new(usb_bus, KeyboardReport::desc(), 1);
let usb_device = UsbDeviceBuilder::new(usb_bus, UsbVidPid(0x1209, 0x0001))
.manufacturer("Foo")
.product("Bar")
.build();
unsafe {
USB_CTX = Some(UsbContext {
usb_device,
hid_class,
current_index: 0,
pressed: false,
indicator: status.downgrade(),
trigger: trigger.downgrade(),
});
}
unsafe { interrupt::enable() };
loop {
sleep();
}
}
static mut USB_CTX: Option<UsbContext<PLL>> = None;
#[interrupt(atmega32u4)]
fn USB_GEN() {
unsafe { poll_usb() };
}
#[interrupt(atmega32u4)]
fn USB_COM() {
unsafe { poll_usb() };
}
/// # Safety
///
/// This function assumes that it is being called within an
/// interrupt context.
unsafe fn poll_usb() {
// Safety: There must be no other overlapping borrows of USB_CTX.
// - By the safety contract of this function, we are in an interrupt
// context.
// - The main thread is not borrowing USB_CTX. The only access is the
// assignment during initialization. It cannot overlap because it is
// before the call to `interrupt::enable()`.
// - No other interrupts are accessing USB_CTX, because no other interrupts
// are in the middle of execution. GIE is automatically cleared for the
// duration of the interrupt, and is not re-enabled within any ISRs.
let ctx = unsafe { USB_CTX.as_mut().unwrap() };
ctx.poll();
}
struct UsbContext<S: SuspendNotifier> {
usb_device: UsbDevice<'static, UsbBus<S>>,
hid_class: HIDClass<'static, UsbBus<S>>,
current_index: usize,
pressed: bool,
indicator: Pin<Output>,
trigger: Pin<Input<PullUp>>,
}
impl<S: SuspendNotifier> UsbContext<S> {
fn poll(&mut self) {
if self.trigger.is_low() {
let next_report = if self.pressed {
BLANK_REPORT
} else {
PAYLOAD
.get(self.current_index)
.copied()
.and_then(ascii_to_report)
.unwrap_or(BLANK_REPORT)
};
if self.hid_class.push_input(&next_report).is_ok() {
if self.pressed && self.current_index < PAYLOAD.len() {
self.current_index += 1;
}
self.pressed = !self.pressed;
}
} else {
self.current_index = 0;
self.pressed = false;
self.hid_class.push_input(&BLANK_REPORT).ok();
}
if self.usb_device.poll(&mut [&mut self.hid_class]) {
let mut report_buf = [0u8; 1];
if self.hid_class.pull_raw_output(&mut report_buf).is_ok() {
if report_buf[0] & 2 != 0 {
self.indicator.set_high();
} else {
self.indicator.set_low();
}
}
}
}
}
const BLANK_REPORT: KeyboardReport = KeyboardReport {
modifier: 0,
reserved: 0,
leds: 0,
keycodes: [0; 6],
};
fn ascii_to_report(c: u8) -> Option<KeyboardReport> {
let (keycode, shift) = if c.is_ascii_alphabetic() {
(c.to_ascii_lowercase() - b'a' + 0x04, c.is_ascii_uppercase())
} else {
match c {
b' ' => (0x2c, false),
_ => return None,
}
};
let mut report = BLANK_REPORT;
if shift {
report.modifier |= 0x2;
}
report.keycodes[0] = keycode;
Some(report)
}