2929
3030namespace SimRacing {
3131
32+ /* *
33+ * Take a pin number as an input and sanitize it to a known working value
34+ *
35+ * In an ideal world this would check against the available pins on the micro,
36+ * but as far as I know the Arduino API does not have a "valid pin" function.
37+ * Instead, we'll just accept any positive number as a pin and reject any
38+ * negative number as invalid ("Unused").
39+ *
40+ * @param pin the pin number to sanitize
41+ * @returns the pin number, or UnusedPin
42+ */
43+ static constexpr PinNum sanitizePin (PinNum pin) {
44+ return pin < 0 ? UnusedPin : pin;
45+ }
46+
3247
3348/* *
3449* Invert an input value so it's at the same relative position
@@ -163,7 +178,7 @@ static void readFloat(float& value, Stream& client) {
163178
164179DeviceConnection::DeviceConnection (PinNum pin, bool invert, unsigned long detectTime)
165180 :
166- Pin (pin), Inverted(invert), stablePeriod(detectTime), // constants(ish)
181+ Pin (sanitizePin( pin) ), Inverted(invert), stablePeriod(detectTime), // constants(ish)
167182
168183 /* Assume we're connected on first call
169184 */
@@ -186,7 +201,9 @@ DeviceConnection::DeviceConnection(PinNum pin, bool invert, unsigned long detect
186201 lastChange (millis() - detectTime)
187202
188203{
189- pinMode (Pin, INPUT); // set pin as input, *no* pull-up
204+ if (pin != UnusedPin) {
205+ pinMode (Pin, INPUT); // set pin as input, *no* pull-up
206+ }
190207}
191208
192209void DeviceConnection::poll () {
@@ -259,7 +276,7 @@ bool DeviceConnection::readPin() const {
259276
260277
261278AnalogInput::AnalogInput (PinNum p)
262- : Pin(p ), position(AnalogInput::Min), cal({AnalogInput::Min, AnalogInput::Max})
279+ : Pin(sanitizePin(p) ), position(AnalogInput::Min), cal({AnalogInput::Min, AnalogInput::Max})
263280{
264281 if (Pin != UnusedPin) {
265282 pinMode (Pin, INPUT);
@@ -662,17 +679,19 @@ AnalogShifter::AnalogShifter(PinNum pinX, PinNum pinY, PinNum pinRev, PinNum det
662679 /* In initializing the Shifter, the lowest gear is going to be '-1' if a pin
663680 * exists for reverse, otherwise it's going to be '0' (neutral).
664681 */
665- Shifter (pinRev != UnusedPin ? -1 : 0 , 6 ),
682+ Shifter (sanitizePin( pinRev) != UnusedPin ? -1 : 0 , 6 ),
666683
667684 /* Two axes, X and Y */
668685 analogAxis{ AnalogInput (pinX), AnalogInput (pinY) },
669686
670- PinReverse (pinRev),
687+ PinReverse (sanitizePin( pinRev) ),
671688 detector (detectPin, false ) // not inverted
672689{}
673690
674691void AnalogShifter::begin () {
675- pinMode (PinReverse, INPUT);
692+ if (this ->PinReverse != UnusedPin) {
693+ pinMode (PinReverse, INPUT);
694+ }
676695 update (); // set initial gear position
677696}
678697
0 commit comments