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
use sdl3::get_error;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let sdl_context = sdl3::init()?;
let joystick_subsystem = sdl_context.joystick()?;
let joysticks = joystick_subsystem
.joysticks()
.map_err(|e| format!("can't get joysticks: {e}"))?;
println!("{} joysticks available", joysticks.len());
// Iterate over all available joysticks and stop once we manage to open one.
let mut joystick = joysticks
.into_iter()
.find_map(|joystick| match joystick_subsystem.open(joystick) {
Ok(c) => {
println!("Success: opened \"{}\"", c.name());
Some(c)
}
Err(e) => {
println!("failed: {e:?}");
None
}
})
.expect("Couldn't open any joystick");
// Print the joystick's power level
println!(
"\"{}\" power level: {:?}",
joystick.name(),
joystick.power_info().map_err(|e| e.to_string())?
);
let (mut lo_freq, mut hi_freq) = (0, 0);
for event in sdl_context.event_pump()?.wait_iter() {
use sdl3::event::Event;
match event {
Event::JoyAxisMotion {
axis_idx,
value: val,
..
} => {
// Axis motion is an absolute value in the range
// [-32768, 32767]. Let's simulate a very rough dead
// zone to ignore spurious events.
let dead_zone = 10_000;
if val > dead_zone || val < -dead_zone {
println!("Axis {axis_idx} moved to {val}");
}
}
Event::JoyButtonDown { button_idx, .. } => {
println!("Button {button_idx} down");
if button_idx == 0 {
lo_freq = 65535;
} else if button_idx == 1 {
hi_freq = 65535;
}
if button_idx < 2 {
if joystick.set_rumble(lo_freq, hi_freq, 15000) {
println!("Set rumble to ({lo_freq}, {hi_freq})");
} else {
println!(
"Error setting rumble to ({}, {}): {:?}",
lo_freq,
hi_freq,
get_error()
);
}
}
}
Event::JoyButtonUp { button_idx, .. } => {
println!("Button {button_idx} up");
if button_idx == 0 {
lo_freq = 0;
} else if button_idx == 1 {
hi_freq = 0;
}
if button_idx < 2 {
if joystick.set_rumble(lo_freq, hi_freq, 15000) {
println!("Set rumble to ({lo_freq}, {hi_freq})");
} else {
println!(
"Error setting rumble to ({}, {}): {:?}",
lo_freq,
hi_freq,
get_error()
);
}
}
}
Event::JoyHatMotion { hat_idx, state, .. } => {
println!("Hat {hat_idx} moved to {state:?}")
}
Event::Quit { .. } => break,
_ => (),
}
}
Ok(())
}