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
mqttc.connect(MOSQUITTO_HOST,MOSQUITTO_PORT)

Here is the main run time loop:

while True:
    try:
        mqttc.loop_forever

except Exception,e:
    logging.error("Error in mqtt loop")
    mqttc.disconnect()
    mqttc.connect(MOSQUITTO_HOST,MOSQUITTO_PORT)
    continue

except KeyboardInterrupt:
    print("error")
    GPIO.cleanup()
    exit(0)

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

def on_message(client, userdata, msg):
    logging.info('Topic: ' + msg.topic+' Message: '+str(msg.payload))
    if msg.payload == "1":
        logging.info("Turning Fan on")
        fan.ChangeDutyCycle(100)
        (result1,mid) = client.publish("cupboard/fanstate","ON")
    else:
        logging.info("Turning fan off")
        fan.ChangeDutyCycle(0)
        (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):
    logging.info("Connected with result code "+str(rc))
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe('cupboard/fan',1)

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:
OpenHAB and Bluetooth beacons for temperature (Blue Maestro Tempo Disc)






Comment by timmmay, on 26-Jan-2017 08:11

Alternately this US$7 thermal switch will do the job just fine :)


Author's note by davidcole, on 26-Jan-2017 09:14

But no pretty LCD display... :D


Add a comment

Please note: comments that are inappropriate or promotional in nature will be deleted. E-mail addresses are not displayed, but you must enter a valid e-mail address to confirm your comments.

Are you a registered Geekzone user? Login to have the fields below automatically filled in for you and to enable links in comments. If you have (or qualify to have) a Geekzone Blog then your comment will be automatically confirmed and placed in the moderation queue for the blog owner's approval.

Your name:

Your e-mail:

Your webpage:

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, 10921 views)
eReceipts - Why don't we have ...
(12-Jan-2012 10:01, 8249 views)
PDF Forms - why you no boxes?...
(26-Jun-2012 09:04, 7459 views)
Free $80 - come and get ur mon...
(20-Sep-2011 13:11, 7099 views)
Contactless Payments - part 2...
(21-Sep-2011 15:12, 4837 views)
Little Boys and their Sewing M...
(27-Dec-2009 11:09, 4827 views)
OpenHAB and Bluetooth beacons ...
(19-Dec-2016 21:39, 4498 views)
TVNZ Ondemand App behind Unblo...
(1-Mar-2013 07:14, 3899 views)
Controlling a 12v fan from a r...
(17-Jan-2017 07:49, 3623 views)
Americans Scare me........
(13-Nov-2008 08:37, 3431 views)