I am trying to do an Internet of Things project with the help of a Raspberry Pi. While most of the project is complete, there is one small thing I am stuck at. I need to connect a solenoid valve to the Pi. The valve needs a voltage of 24v-36v to operate. I connected three 9v batteries together in series to operate it. The valve opens when the voltage is applied and closes when it not. I want to control the opening and closing of the valve by the Pi’s GPIO pins. I’m using a NPN 2N3904 transistor for that. The circuit I’m using is exactly the one given in this image. http://www.davidhunt.ie/water-droplet-photography-with-raspberry-pi/ (http://www.davidhunt.ie/water-droplet-photography-with-raspberry-pi/)

However, it’s not working. The circuit works sometimes and doesn’t work other times when I manually pull and put in the GPIO pin. It never works with code. Is the 27v causing problems with the Pi? What can I do? Is there another way to control it apart from NPN transistors?

The code:

import RPi.GPIO as GPIO
import time,os



  • 2
    On a side note: flyback diode (flywheels are something different).
    – Ghanima
    Apr 21 '16 at 15:48
  • 1
    And you show 12v not 24v, but other than that identical Apr 21 '16 at 15:52
  • 1
    Can we see the code? Apr 21 '16 at 15:53
  • 1
    GPIO pins can source 2-12mA, but you have to configure them. 2mA are more than enough to drive the 2N3904 to saturation.
    – JayEye
    Apr 21 '16 at 16:30
  • 2
    what is the value of the resistor? How much current does the solenoid need to draw to turn on?
    – JayEye
    Apr 21 '16 at 16:30

I would get rid of all this and just use a ULN2001 or ULN2003, whichever you happen to have around. Then you can drive seven solenoids (but watch out for total current!)

A convenient, although not as cheap as ordering from Mouse or DigiKey, source of ULN2003 is the various "stepper motor driver" boards sold on ebay or aliexpress. You also get four convenient LEDs :)

  • thanks for the suggestion! However, is it fine if instead of an ULN2003, I use a four channel relay optocoupler (ebay.com/itm/…) Apr 23 '16 at 9:14
  • it's a bit of an overkill, using an electromechanical device (relay) to drive another electromechanical device (solenoid), but if you have one around, it will work.
    – JayEye
    Apr 23 '16 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.