Skip to content

Commit bc4e974

Browse files
committed
examples: phoenix-arduino-joystick: use 10 bits per axis
Avoid integer overflow issues by using only 10 bits per axis instead of 16 bits.
1 parent 63ffdf1 commit bc4e974

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

examples/phoenix-arduino-joystick/phoenix-arduino-joystick.ino

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@
66

77
const size_t kNumAxes = 4;
88
using AxesValueType = int16_t;
9-
const AxesValueType kAxesMin = -32768;
10-
const AxesValueType kAxesMax = 32767;
9+
#define AXIS_BITS 10
10+
const AxesValueType kAxesMin = (-1 << (AXIS_BITS - 1));
11+
const AxesValueType kAxesMax = -kAxesMin - 1;
1112

1213
const size_t kNumButtonGroups = 3;
1314

@@ -19,6 +20,10 @@ struct ReportData {
1920

2021
using namespace usb::hid;
2122

23+
constexpr uint8_t GetByte(int16_t x, uint8_t b) {
24+
return (x >> (b << 3));
25+
}
26+
2227
const u8 kReportId = 1;
2328
static const u8 sHidDescriptorData[] PROGMEM = {
2429
Global::UsagePage | 1, usage::Page::GenericDesktop,
@@ -34,9 +39,14 @@ static const u8 sHidDescriptorData[] PROGMEM = {
3439
Local::Usage | 1, usage::generic_desktop::Axis::Y,
3540
Local::Usage | 1, usage::generic_desktop::Axis::Rz,
3641
Local::Usage | 1, usage::generic_desktop::Axis::Z,
37-
Global::LogicalMinimum | 2, 0x00, 0x80, // kAxesMin = -32768
38-
Global::LogicalMaximum | 2, 0xFF, 0x7F, // kAxesMax = 32767
39-
Global::ReportSize | 1, 16,
42+
#if AXIS_BITS > 8
43+
Global::LogicalMinimum | 2, GetByte(kAxesMin, 0), GetByte(kAxesMin, 1),
44+
Global::LogicalMaximum | 2, GetByte(kAxesMax, 0), GetByte(kAxesMax, 1),
45+
#else // AXIS_BITS <= 8
46+
Global::LogicalMinimum | 1, kAxesMin,
47+
Global::LogicalMaximum | 1, kAxesMax,
48+
#endif
49+
Global::ReportSize | 1, sizeof(AxesValueType) * 8,
4050
Global::ReportCount | 1, 4,
4151
Main::Input | 1, DataBits::Variable,
4252
Main::EndCollection | 0,

0 commit comments

Comments
 (0)