From 0e898d5e03eac5f0a42e658a35a57e758bf7e36a Mon Sep 17 00:00:00 2001
From: Victor Aprea <victor.aprea@wickeddevice.com>
Date: Sun, 15 Feb 2015 17:56:48 -0500
Subject: [PATCH] Do not influence state of SS if it's already been set to an
 output previously, e.g. by user sketch

squashes and closes PR #2659
---
 hardware/arduino/avr/libraries/SPI/SPI.cpp | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/hardware/arduino/avr/libraries/SPI/SPI.cpp b/hardware/arduino/avr/libraries/SPI/SPI.cpp
index 9e7a11679..af14e07b1 100644
--- a/hardware/arduino/avr/libraries/SPI/SPI.cpp
+++ b/hardware/arduino/avr/libraries/SPI/SPI.cpp
@@ -29,7 +29,15 @@ void SPIClass::begin()
   noInterrupts(); // Protect from a scheduler and prevent transactionBegin
   if (!initialized) {
     // Set SS to high so a connected chip will be "deselected" by default
-    digitalWrite(SS, HIGH);
+    uint8_t port = digitalPinToPort(SS);
+    uint8_t bit = digitalPinToBitMask(SS);
+    volatile uint8_t *reg = portModeRegister(port);
+
+    // if the SS pin is not already configured as an output
+    // then set it high (to enable the internal pull-up resistor)
+    if(!(*reg & bit)){
+      digitalWrite(SS, HIGH);
+    }
 
     // When the SS pin is set as OUTPUT, it can be used as
     // a general purpose output port (it doesn't influence