Connecting a switch and a MOSFET to an Arduino? I have an LED strip that I am trying to turn on with a magnetic switch when a door opens. I want the LEDs to fade on when I open the door and fade off when I close it, which is where the Arduino comes in. I am using PWM for the fading. I can get each component to work separately. The fading LEDs work with the MOSFET without the switch. I tested the switch with serial output on the Arduino and it works fading a single LED without the MOSFET.  

I am using:


Arduino Uno R3
Magnetic Switch
N-Channel MOSFET IRLB3034
5 Meter White LED Strip
12VDC 30W Power Supply
10k Ohm Resistors  


My setup looks like this:


Schematic:


Code (if it helps):  

const int buttonPin = 2;     // the number of the switch pin
const int ledPin =  9;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the switch status
int brightness = 0;
int fadeAmount = 5;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);      
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);     
}

void loop(){
  // read the state of the switch value:
  buttonState = digitalRead(buttonPin);

  // check if the switch is ON.
  // if it is, the buttonState is LOW:
  if (buttonState == LOW) {     
    // fade LED on:    
    analogWrite(ledPin, brightness);  
    if (brightness &lt; 255) {
      brightness = brightness + fadeAmount;
    }
  } 
  else {
    // fade LED off:
    analogWrite(ledPin, brightness); 
    if (brightness &gt; 0) {
      brightness = brightness - fadeAmount;
    }
  }
  delay(30);
}


I have a feeling the problem is with the common ground on the MOSFET and the switch. Any solutions/suggestions are appreciated.
I think you should keep the R2 resistor, but make it 1k and put before it a pull-down resistor of 10k so that any charges stored in the NMOS Cgate capacitance are discharged, whenever there is High-Z at the port D9. Also never forget the resistor limiting the diode forward current, which is typically 20 mA, but you should check that every time in datasheet. In case of LED strip there are usually internal resistors, but if you are using higher voltage still you need to restrict the current. Could you tell us more about why you are using PWM not a simple output port with an integrator for example and what you exactly observe and measure when you turn-on-off (fade-on-off) the LED?







simulate this circuit &ndash; Schematic created using CircuitLab

How to make the diagram a bit smaller?