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.

OpenHAB and Bluetooth beacons for temperature (Blue Maestro Tempo Disc)

, posted: 19-Dec-2016 21:39

Recently I've dipped my toes in the home automation pool.

I started out with an OpenHab installation on linux, then started adding some sensors.

The easy ones were existing items already compatible and computer based, NUT for UPS, Plex and with a bit of effort server load, temp and memory usage.

I had a couple of raspberry Pis floating around, so after some reading I added a 1 or 2 DHT22 sensors (  Including one raspberry pi with 2 sensors.  These work well with MQTT and feed in both temperature and humidity.

But doing that required a fair bit of wiring, and a raspberry pi with power costs around the $80 NZD mark, so I start looking a iBeacons, as some include temperature sensors.  The idea being I would have a central device (a Rasbperry Pi most likely), with a bluetooth receiver, and it would take a feed from a number of bluetooth based sensors.

I received one, but could never get the temperature sensor to activate and the support was a little lacking.

Then I stumbled across Blue Maestro ( .  They sell "smart" pacifiers and environmental sensors, all using Bluetooth LE.  After some back and forth discussing how they work and their intended use, I purchased a Tempo Disc (

It came with a link to an IOS app for pulling the internal data via bluetooth. 

So after looking at it on and off for a couple of months, and with a release on an updated API document, I finally found a set of commands for reading the raw data off the unit without having to make a proper connection.

For some background a bluetooth device will push out advertising packets at defined intervals.  These include the MAC address, the UDID of the device and version numbers.  But also hidden in another packet is some of the specific manufacturer information and specific instructions, in this case temperature, humidity and dewpoint numbers.

After a lot of trial and error I finally found that wireshark would read a bluetooth dump.


sudo hcidump -w btle.cap

On one SSH session and

sudo hcitool lescan --duplicates

on a second would create a dump file that you could then load into to wireshark.  The 2nd command is a bluetooth scan.  Its sends out requests for all devices in range and the response from each device is generally 1 or 2 advertising packets (SCAN_RSP - defined by the hex 04 at the start).

Before I found wireshark, at this point all I would see was a dump of hex:

04 3e 2a 02 01 04 01 xx xx xx xx xx xx 1e 1d ff 33 01 00 d9 02 ae 00 c0 02 41 00 d9 02 ae 00 93 00 c0 02 41 00 80 00 d0 02 82 00 89 b8

A blog post a read said that Wireshark could load a dump file from hci dump and interrogate the packets.  This made life so much easier to decode the packets, as you saw the hex and ascii.

This is the first packet (above).  It contains the mac address (in reverse).  There's no specific sensor information in this packet though.

The interesting one is the 2nd one:

04 3e 2b 02 01 00 01 xx xx xx xx xx xx 1f 02 01 06 11 ff 33 01 16 5e 0e 10 00 08 00 bf 02 b0 00 81 01 00 09 09 54 65 6d 70 48 75 6d 33 b3

This one also contains the mac address, and at the far right is actually the devices' name, Preceded by the length of the name.  In this case it's 9 characters and is 54, 65, 6d, 70, 48, 75, 6d, which when you convert to ASCII is "TempHum3"

The interesting data is in the middle though. 00 bf (28-29) is the temperature in hex. so 00 bf converting to decimal is 191 - or 19.1 Degrees.  Following, the 02 bf, is the humidity, or 688 decimal, or 68.8% and lastly is the dewpoint, 00 81 or 129 = 12.9 Degrees.

Once I had that then I knocked together a quick python program which will pull the advertising packets and put the mac address, temperature, battery, humidity and dewpoint into an object.

Company: 3301
UDID: a700d0025e00820100090954656d
MAJOR: 70 48 None
MINOR: 75 6d None
Temp: 00d0
Temp: 20.8
Humidity: 02 5e None
Humidity: 60.6
Dewpoint: 13.0
NameLength: 9
Name: TempHum3 9
Battery: 57 None
Battery: 87.3411764706

I also tested for the company id, which which is the blue maestro company identifier for this specific packet.

Then a send python script calls this one every 10 mins, if the packets are returned then I use MQTT to push the data to openhab.  At this point I used the mac address as a main topic...and push the name also.  Meaning what ever name I give the device is independent to the mac address and can be use for defining the room.

When it's all complete it looks as follows in OpenHAB;

So now that it's in OpenHab I can move to centralise the collection of environmental data to a couple of raspberry pis.

 I'm intending to put the code on github and will link to it when done.  The outer is generic, but the inner class is specific to these Blue Maestro discs.  But could be adapted for any type of similar device as long at it also used the advertising packets.

 UPDATE: Here's a link to github.  Both python files in this folder are required. Link Here


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