Skip to content

Check for valid pin properly (fixes #4605) #4649

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions hardware/arduino/avr/cores/arduino/wiring_digital.c
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,16 @@
#include "wiring_private.h"
#include "pins_arduino.h"

#define PIN_MAX (sizeof digital_pin_to_port_PGM / sizeof *digital_pin_to_port_PGM)

void pinMode(uint8_t pin, uint8_t mode)
{
uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);
if (pin >= PIN_MAX) return;

uint8_t bit = digitalPinToBitMask(pin); // bit mask, or 0 for invalid pins
uint8_t port = digitalPinToPort(pin); // must be a valid port (even for invalid pins)
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);
Expand Down Expand Up @@ -137,13 +139,13 @@ static void turnOffPWM(uint8_t timer)

void digitalWrite(uint8_t pin, uint8_t val)
{
if (pin >= PIN_MAX) 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);
Expand All @@ -164,12 +166,12 @@ void digitalWrite(uint8_t pin, uint8_t val)

int digitalRead(uint8_t pin)
{
if (pin >= PIN_MAX) 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);
Expand Down