Controlling a 12v fan from a raspberry Pi.

, posted: 17-Jan-2017 07:49

My last post (Here), showed the reading of temperatures via raspberry Pi. The last post it was via a Bluetooth dongle and a BlueMaestro temp disc.

Once you've taken the temperature, or other sensor readings, it's now time to do something with it.

My Comms cabinet is in an external cupboard and wall mounted. It's one disadvantage, that on a sunny day, the sun beats on to the door and warms the room up, so I grabbed two 120mm fans, mounted them on to a bracket, and hooked them up to a 12v AC adapter. It works well, but I realised that it didn't need to be on 24x7. So I started investigating options for tying the fans to the temperature.

Initially I tried an external thermostat. As an idea it was great (12V Digital Thermostat Temperature Alarm Controller). On execution the one I'd bought didn't seem to work, as even though it powered, when triggered I was getting no voltage on the output terminals. Disappointing, but led me to look harder at raspberry Pi based methods. Then I stumbled across some posts on mosfet relays, and the use of Pulse width modulation. 0-24VTop Mosfet Button IRF520 MOS Driver Module For Arduino MCU ARM Raspberry pie.

Upon receiving the relay, I quickly wired a DC 2.1 barrel and socket knowing that I could plug it into the fan that already used that connector and a battery also with a similar connector, or into a voltage regulator as shown below. Then I found some python code that used the PWM pin on the raspberry Pi (pin 18) and controlled an LED light from 0 to 100 and back.


The mosfet relay is wired as follows:

VCC (positive) to pi. 2 (white)
GND (negative) to pin 4 (black)
SIG (signal) to pin 12 (this is a raspberry pi's PWM port GPIO 18) (gray)

After testing with a fan that it would actually drive the two fans, I started the interface to OpenHAB

I'll start with the OpenHAB items, so you can see where the mqtt topics are entered.

Switch gf_cupboard_fan "Fan Control [%s]" <socket>  {mqtt=">[mosquitto:cupboard/fan:command:ON:1],>[mosquit to:cupboard/fan:command:OFF:0],<[mosquitto:cupboard/fanstate:state:default]"}

So this item has a couple of components.

  • First it's a switch
  • Its name (when accessing via sitemap, or as a command) is gf_cupboard_fan.
  • <socket> is the icon to use.

The next bits are the mosquitto bindings. I'll have to assume you know a little about this already.

But in essence this one says that openhab will push (defined by the >) to a subscribed item on the topic cupboard/fan, 1 for ON and 0 for OFF when the switch is acted upon, by the user in the OpenHAB interface. The next part with the < is an input on a topic cupboard/fanstate. This will receive a status back from the fan control script.

Next up is the script that will both subscribe to the control topic (cupboard/fan) and the publish the state back to openhab - cupboard/fanstate.

The script can be found here: Github Link

I'll post the main sections - warning, this isn't as parameterised as some if the other scripts I have. If I install another instance then I'll add a lot more configuration parameters.

After the two callback methods, on_message and on_connect, setup up the mosquito server and gpio ports.

set the loop time
PAUSE_TIME = 60.02

Create the mosquito client, asking the callback messages, and connect to the server.

mqttc = mqtt.Client()
mqttc.on_message = on_message
mqttc.on_connect = on_connect

Here is the main run time loop:

while True:

except Exception,e:
    logging.error("Error in mqtt loop")

except KeyboardInterrupt:

There very little to it, as the work is in the on_message callback.

def on_message(client, userdata, msg):'Topic: ' + msg.topic+' Message: '+str(msg.payload))
    if msg.payload == "1":"Turning Fan on")
        (result1,mid) = client.publish("cupboard/fanstate","ON")
    else:"Turning fan off")
        (result1,mid) = client.publish("cupboard/fanstate","OFF")

If "1" is received as the message to the subscribed topic of cupboard/fan, the message is logged, and a ON state is posted back to OpenHAB to update the GUI (if the message has been fired external to the openhab GUI, ie a rule. If 0 received then the reverse.

def on_connect(client, userdata, rc):"Connected with result code "+str(rc))
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.

The on connect method just subscribes to the topic where openhab will post the on/off command.

The last bit is the control, I have a GUI item for the switch. The is what can receive the state, and push the 1/0 state.

I also have a rule that runs whenever a specified temperature sensor is updated. The temperature is analysed, and when above a threshold the fan switch is sent an ON command. When below a minimum, an OFF is sent.

Other related posts:
RM3's also - but this time with more geek.
OpenHAB and Bluetooth beacons for temperature (Blue Maestro Tempo Disc)

comments powered by Disqus

davidcole's profile

davidcole Cole
Lower Hutt
New Zealand

Been thinking it would be nice to have a blog but not sure if I have enough to say.

I'm an I.T worker from Wellington New Zealand.

I like my toys so this will probably have posts about my dealings with those.

My Cellphone is an iPhone 5s

I run a NextPVR based PVR at home to replace my video recorder, DVD player and to host all my music. I'm also really big on Plex, for centralising all my music, videos and I've written a plugin or two for it for accessing live TV and for storing recordings with metadata.

TVNZ Ondemand App behind Unblo...
(27-Feb-2013 19:39, 11583 views)
eReceipts - Why don't we have ...
(12-Jan-2012 10:01, 8935 views)
Controlling a 12v fan from a r...
(17-Jan-2017 07:49, 8803 views)
OpenHAB and Bluetooth beacons ...
(19-Dec-2016 21:39, 8768 views)
PDF Forms - why you no boxes?...
(26-Jun-2012 09:04, 8086 views)
Free $80 - come and get ur mon...
(20-Sep-2011 13:11, 7727 views)
Contactless Payments - part 2...
(21-Sep-2011 15:12, 5381 views)
Little Boys and their Sewing M...
(27-Dec-2009 11:09, 5327 views)
TVNZ Ondemand App behind Unblo...
(1-Mar-2013 07:14, 4536 views)
RM3's also - but this time wit...
(16-Jul-2017 20:16, 4357 views)