How we made a home cooling fan smart with JavaScript

codebeast

Christian Nwamba

Posted on November 18, 2019

How we made a home cooling fan smart with JavaScript

(This article is co-authored by Chinedu Imoh)

Our friend had a damaged fan — the fan’s control board got fried. We were tired of seeing it lie around the house when we visit her on weekends but recycling electronics in Nigeria is not a thing.

We thought, instead of harming the world by throwing the fan away, we could just pull out the damaged board, join the wires under the hood manually and still have the fan work.

With a flat screw driver, as seen in the picture on the right, we pulled out the control panel of the board and cut out the wire from the board.

Pulled out control chip (the actual damaged fan is a black one — we got a white one that’s good)

At this point joining a couple of wires would get the fan back to live but it’s the era of IoT and we thought to ourselves — “this is a free fan we could play with, what can we do?”

Well it didn’t take us too long to REALIZE that with a Tessel 2 and a relay, we cloud turn this so-called damaged fan into one of the smartest device in our friend’s home.

This article outlines our journey to how we made this fan smart. At the end, you will learn:

  1. What requirements we used to make this fan smart
  2. How we used a relay to interface this fan with a Tessel IoT board
  3. How we controlled this fan with a computer (can be a phone) through a Tessel board

The best way to follow this article is to get the same devices we used but of course you might not have that luxury. This is why we are structuring this post in a way that you can apply what ever you learn in your IoT journey — regardless of whether:

  1. This is your first look at IoT or
  2. You have been doing IoT stuff but want to learn how to control home appliances with IoT

Requirements

This upcoming list does not have to be followed religiously and you can replace each part with what ever works best for you:

  1. A room fan — we are using Honeywell QuietSet Fan
  2. Tessel 2 IoT Board
  3. Saint Smart Relay
  4. Jumper Cables
  5. Basic knowledge of JavaScript/Node

You can buy a Tessel kit which comes with Tessel 2, cables, few sensors, etc. The relay and fan does not come with the kit but you can get those from the links.

Circuit Diagram

We are totally aware that this article targets both developers as well as electrical engineers. With this in mind, we chose to not draw a professional circuit diagram but a simpler flow diagram of what the connections look like.

The secondary reason for not making a professional circuit diagram is because we both have computer programming background and suck terribly at such.

The only thing you should care about are the wires we pulled out of the control chip. That said, feel free to skip the next section if you don’t want to understand where those wires poking out of the fan came from.

How the fan works

The components that make up the mechanics of the fan are:

  1. A big fan motor
  2. A capacitor
  3. A small fan motor(for swing/rotation)
  4. Power source

The big fan motor has five multi-coloured wire’s — two(green) are connected to the capacitor, the next two(yellow and red) are connected to the chip (which we pulled out), and the last one(white) is connected to the smaller motor which in turn also goes to the board.

Capacitors are devices which store electrical charge, a motor capacitor, such as a dual run capacitor is an electrical capacitor that alters the current to one or more windings of a single phase AC induction motor to create a rotating magnetic field. In this case both(green) wires of the capacitor are connected to the big fan motor to run both motors.

The small fan motor is used to rotate the body of the fan so as to distribute air to the room. Both blue and black of the small fan motor wires are taken the board, but the blue is first connected to the big fan before getting connected to the board.

The 2 power source (140V wire’s) both go straight to the board.

In summary with regard to the wires we pulled out, the white and the the blue are used by the relay to toggle the fan while the black and yellow are used to toggle the swing. The remaining two wires (red and brown) can be used to toggle both power and swing at once.

Setting up Tessel 2

Install the Tessel 2 node module using the following command:

npm install -g t2-cli
Enter fullscreen mode Exit fullscreen mode

Plug in the Tessel to your computer using the provided USB cable. You can refer to the following image to see how this connection should be made:

It takes 30 seconds to finish booting — at this stage a light will blink until booting is completed. After the Tessel is done booting, run the following command to find it:

t2 list
Enter fullscreen mode Exit fullscreen mode

You should see a message like the one below:

INFO Searching for nearby Tessels...
  USB Tessel-AF768F095
Enter fullscreen mode Exit fullscreen mode

USB means it’s connected via USB. You can connect via wifi which we will see soon.

Tessel-AF768F095 is the name of the Tessel. You can choose to rename it with:

t2 rename <name>
Enter fullscreen mode Exit fullscreen mode

Where <name> is the new name. Running t2 list again will list the Tessel but with its new name:

INFO Searching for nearby Tessels...
  USB HomeFan
Enter fullscreen mode Exit fullscreen mode

Connect Tessel to Wifi
Connecting to wifi is pretty straightforward — with the Tessel still connected to your computer, run the following command:

t2 wifi -n <network-name> -p <password>
Enter fullscreen mode Exit fullscreen mode
  • <network-name> is the wifi SSID or network name
  • <password> is the wifi password

We have tried connecting to a hotel wifi and it didn’t work. If that’s the kind of network you are on, I am not sure you will have the best luck connecting.

You can choose to push your JS code to Tessel using wifi instead of USB. To set that up, run the following command:

t2 provision
Enter fullscreen mode Exit fullscreen mode

With that in place, you can run t2 list again to confirm wifi is authorized. You see the following:

INFO Searching for nearby Tessels...
        HomeFan        LAN
        HomeFan        USB
Enter fullscreen mode Exit fullscreen mode

Board connections

If you can join legos, you can totally do this kind of connections.

SAFETY WARNING — PLEASE READ
Before you move on, I would like to warn you that the relay is a high voltage device. Once connected to the fan and the fan is powered, there are chances of being electrocuted if you skin gets in contact.

Tessel 2 ←→ Relay

Before we move on with any connection, this is what a Tessel 2 board and our Relay looks like:

Tessel 2 and Saint Smart Relay

A note on both…

The Tessel is the CPU of our setup. This is what we will ship JavaScript to setup a network access point, control the I/O devices (eg the relay) etc. Basically, this is the board that replaces the chip we pulled out earlier.

The black rectangle plunging out of the board (picture coming soon below) is where you connect your input and output devices. This is where we will connect the relay to. You can also connect sensors, displays, and other accessories using this port.

The saint smart 4 pin relay module is a separate hardware device that takes instruction from a 5v chip, for example Tessel 2, and uses the instruction to control high voltage devices of up to 240v (eg. fan). With out the relay the micro-controller can only control devices of 5v and below.

We need to get the connection right for this relay — here is a connection diagram:

Tessel 2 and Relay port mapping

With the jumper cables, connect the 0 port of the Tessel to IN1 port of the relay. Do that for the rest of the ports as mapped below:

  • 0 ←→ IN1
  • 1 ←→ IN2
  • 2 ←→ IN3
  • 3 ←→ IN4

The following image shows the required wiring between the Tessel and the relay:

Showing I/O connection as well as GND and 5v connection for relay

The first thing that will throw you off is that we have a blue and brown cable running out of the GND and VOC ports, respectively. These GND port stands for ground and that is how you ground the relay. This means you need to connect it to the GND of the Tessel 2. The VOC is 5v power source for the relay and it has to go to the 5v port of the Tessel as well.

On the Tessel 2, here is how the blue and brown cables run into the Tessel’s GND and 5v ports:

GND and 5v connection

Relay ←→ Fan

We have seen how to connect the IoT board to the relay, now we need to connect the relay to the fan:

Programming the Tessel 2

We want to be able to control the fan from our phones and laptops. One way we can do this is to have a node server run on the Tessel. This is totally possible. You can have a usual node server run on Tessel and access the Tessel from an IP address.

With all your connections still in place, make sure the Tessel is connected to your computer and run t2 list to make sure it’s all setup.

To create a code project, cd into the folder you want to code to live and run the following

t2 init && mkdir public
Enter fullscreen mode Exit fullscreen mode

This will setup a Tessel project with a package.json file. It will also create a public folder for the browser client app.

Install the following node packages:

npm install --save express body-parser socket.io tessel tessel-gpio-relay
Enter fullscreen mode Exit fullscreen mode

A node server

Create a server.js file in the root of your Tessel project with the following content:

// Dependencies
const path = require('path');
const relaylib = require('tessel-gpio-relay'); 
const tessel = require('tessel')
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);

// PORT
const port = process.env.PORT || 80;

// Setup relay ports
const relay = relaylib.use(tessel.port['B'], [1,2]); 

// Express middlewares
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({ extended: true }));

// Server public folder as static content folder
app.use(express.static(path.join(__dirname, 'public')));

// Index page route
app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '/public/index.html'));
});


//// websocket code coming soon...


http.listen(port, function() {
  console.log(
    'Your server is up and running on Port ' + port + '. Good job!',
  );
});
Enter fullscreen mode Exit fullscreen mode

This is an express middleware and what is going on is beyond the scope of this article. In summary, we have setup an express HTTP app and a websocket using socket.io. The app.get route responds to the index requests sent to our server.

Note how we are using the relay library and the Tessel library to setup a port on the Tessel and map it to the relay IN1 and IN2.

As for the content shown in the index.html, create an index.html file in the public folder with the following:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Set a Color</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1 id="state">Set Mode</h1>
  <form method="POST" action="">
    <input type="button" onClick="operacion1()" value="FAN"></input>
    <input type="button" onClick="operacion2()" value="SWING"></input>
  </form>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.dev.js'></script>
  <script src="script.js"></script>
  <script>
    const socket = io();
    const modePicker = document.getElementById('statePicker');
    function operacion1(){
      socket.emit('fanChange', 'CHANGE');
    }
    function operacion2(){
      socket.emit('swingChange', 'CHANGE');
    }
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Two controls — fan and swing represented and buttons. The intention is that when FAN is clicked, the fan should go on but when SWING is clicked, the fan would start swinging to spread across the room.

The buttons have event listeners on them calling operation1 and operation2 respectively.

In the script file, we are using socket .io to emit events on the websockes back to the server. Now we need to go back to server.js to listen to the events.

Kicking the relay

Once the events are emitted from the web app, we need to listen to it and toggle the relay:

io.on('connection', socket => {
  console.log('Connected...');
  socket.on('fanChange', data => {  
    relay.toggle(1, function toggleOneResult(err) {
      if (err) console.log("Err toggling 1", err);
    });
  });
  socket.on('swingChange', data => {
    relay.toggle(2, function toggleOneResult(err) {
      if (err) console.log("Err toggling 1", err);
    });
  });
});
Enter fullscreen mode Exit fullscreen mode

When the event is received, we can either toggle the IN1 of the relay to start or turn off the fan, we can also make the fan swing or not with IN2.

Starting the Tessel

Before we run the Tessel, we need to find the IP address to reach it with. To get the IP, run the following command:

t2 wifi
Enter fullscreen mode Exit fullscreen mode

This will take print the network information of your Tessel including the IP address:

INFO Looking for your Tessel...
INFO Connected to HomeFan.
INFO SSID: wifi.com.ng Beast
INFO IP Address: 192.168.4.110
INFO Signal Strength: (61/70)
INFO Bitrate: 58 Mbps
Enter fullscreen mode Exit fullscreen mode

Copy the IP address, then run the following:

t2 run server.js
Enter fullscreen mode Exit fullscreen mode

Make sure your computer or phone is on the same wifi network with the Tessel 2 then visit the IP address and you should see the app. Click the fan button to turn on the FAN and you can also swing using the SWING button.

What’s Next?

If you followed to this point, then you have done all the hard work it takes to make a smart device. The next thing you would want to try is to control your device from a different network. Currently we rely on the computer/phone to be on the same wifi as the Tessel — most times, this is totally fine.

Sometimes though, you want to be able to control your device when you are not at home. To do this you need to connect your IoT to a hub. You can apply the technique in this article to connect your device to IoT hub and control it from a cloud.

You can also use temperature sensors to start or stop this fan based on the temperature of the room.

To get your setup for the next post, I strongly suggest you take this ~40mins hands on workshop on serverless functions.

💖 💪 🙅 🚩
codebeast
Christian Nwamba

Posted on November 18, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related