Friday, January 24, 2014

How to use an NPN transistor as a switch with your Arduino

If you've ever wanted to control devices that use higher voltages or require more current than your Arduino can provide, you should try using a transistor! By using a transistor, you can use an external power supply to power up whatever it is you're trying to do. For example, if you wanted to light up 50 leds with an Arduino, you probably couldn't do that because it can't source enough current to be able to allow them to light up. If we used a transistor, we could use a separate power supply that can source enough current for our leds, and be able to control it just like we would control any other Arduino pins. There are two main types of transistors. NPN and PNP. I'm using an NPN transistor called the 2N3904 for my project.

A project I did was create a simple light bar that fades in and out. I used 10 leds, and each led sources about 17mA. So ten leds would be 170mA, which an Arduino pin can't do. So I used a transistor to supply power to them using a 5V wall adapter, and Arduino to fade them in and out.
The code for it is super simple, and probably something you've used before.

#define tranPin 6 //Base is connected to pin 6
void setup() {
  pinMode(tranPin, OUTPUT);
void loop() {
  for (int i=0; i<255; i++) {
    analogWrite(tranPin, i);
  for (int i=255; i>0; i--) {
    analogWrite(tranPin, i);

There are three pins on an NPN transistor. Emitter, Base, and Collector. When holding a transistor with the flat side facing you, it goes (from left to right) Emitter Base Collector. The Base pin is what decides if current will pass from the Collector to the Emitter. Since the transistor is a current controlled device, you MUST have a resistor with the Base. While I was wiring up this circuit before writing this post, I smelled smoke, and realized I had forgotten to put a resistor before the base, luckily I had just purchased 50 of them!

Another great use for transistors with an Arduino is for motors. Since motors can spit a current back out after you remove power from it, it can damage your Arduino. But if you use a transistor to connect to the motor instead of the motor being connected directly to your Arduino, it acts as a shield and won't damage your Arduino.

You can see how it's wired up and acts as a switch when you see it in the Fritzing image.
In the case of the Frtizing image. We're using a 5 volt Arduino, to control the flow of current from a 9 volt battery to the motor. Start your circuit like normal, connect your external power supply (9 volt battery) to your circuit, but connect the ground of the circuit to the Collector, and the Emitter to ground.

And here's the physical circuit. You can see than I'm using a power supply running off of 5 volts for the led, and the Arduino's Vout pin to use on the base to let current pass through the transistor at the base.

If you have any questions feel free to leave a comment below or reach out to me on Google+