From 02a670c867c4e1632e2aa25fc8eefc323045797c Mon Sep 17 00:00:00 2001 From: cousteau Date: Sat, 27 Feb 2016 17:25:53 +0100 Subject: [PATCH] Check for valid pin properly (fixes #4605) Current behavior: look up pin number in `digital_pin_to_port_PGM[]` and then check if it magically returned 0. Proposed behavior (from issue #4605): check if pin is within the valid range, and THEN look it up. Don't check afterwards. IMPORTANT NOTE: This change assumes that `digital_pin_to_port_PGM[]` doesn't skip any pin, which until now could have been done by assigning NOT_A_PIN to the position to skip. If it is planned to have boards where the pin numbering behaves like this, the `if (port == NOT_A_PIN) return;` part should be kept as well (assuming that `NUM_DIGITAL_PINS` will count the "holes" too). --- hardware/arduino/avr/cores/arduino/wiring_digital.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/hardware/arduino/avr/cores/arduino/wiring_digital.c b/hardware/arduino/avr/cores/arduino/wiring_digital.c index 27a62fc6cde..bf91fff2fc2 100644 --- a/hardware/arduino/avr/cores/arduino/wiring_digital.c +++ b/hardware/arduino/avr/cores/arduino/wiring_digital.c @@ -28,12 +28,12 @@ void pinMode(uint8_t pin, uint8_t mode) { + if (pin >= NUM_DIGITAL_PINS) return; + uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); volatile uint8_t *reg, *out; - if (port == NOT_A_PIN) return; - // JWS: can I let the optimizer do this? reg = portModeRegister(port); out = portOutputRegister(port); @@ -137,13 +137,13 @@ static void turnOffPWM(uint8_t timer) void digitalWrite(uint8_t pin, uint8_t val) { + if (pin >= NUM_DIGITAL_PINS) return; + uint8_t timer = digitalPinToTimer(pin); uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); volatile uint8_t *out; - if (port == NOT_A_PIN) return; - // If the pin that support PWM output, we need to turn it off // before doing a digital write. if (timer != NOT_ON_TIMER) turnOffPWM(timer); @@ -164,12 +164,12 @@ void digitalWrite(uint8_t pin, uint8_t val) int digitalRead(uint8_t pin) { + if (pin >= NUM_DIGITAL_PINS) return LOW; + uint8_t timer = digitalPinToTimer(pin); uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); - if (port == NOT_A_PIN) return LOW; - // If the pin that support PWM output, we need to turn it off // before getting a digital reading. if (timer != NOT_ON_TIMER) turnOffPWM(timer);