How we made a home cooling fan smart with JavaScript
Tags: iot, javascript
Published: 2019-11-18 08:32:07

(This article is co-authored by [Chinedu Imoh](https://twitter.com/subsensor))

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.


![](https://paper-attachments.dropbox.com/s_B23788B5B4D37FD8498C15BC46E151D1AD791B8685401758D37455E7741B972B_1572355812706_image.png)


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)](https://paper-attachments.dropbox.com/s_B23788B5B4D37FD8498C15BC46E151D1AD791B8685401758D37455E7741B972B_1572356448903_Desktop+HD+Copy.jpg)


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](https://paper.dropbox.com/doc/How-we-made-a-home-fan-smart--AnmO8dJh905BNe0sXjmSC30iAg-EQ7qeVbbvshHvKtUSxccQ)
2. [Tessel 2](https://www.sparkfun.com/products/13841) IoT Board
3. [Saint Smart Relay](https://www.amazon.com/Huayao-Channel-Optocoupler-Arduino-Raspberry/dp/B07DN8DTRW/ref=pd_rhf_se_p_img_4?_encoding=UTF8&psc=1&refRID=ZQPR3F2J63CQ3QHK1EMC)
4. [Jumper Cables](https://www.amazon.com/Elegoo-EL-CP-004-Multicolored-Breadboard-arduino/dp/B01EV70C78/ref=pd_bxgy_img_2/137-5275525-0293105?_encoding=UTF8&pd_rd_i=B01EV70C78&pd_rd_r=f85be21a-e666-486b-bcbd-e87dcb7bc6c8&pd_rd_w=Gs2FZ&pd_rd_wg=LFkx4&pf_rd_p=09627863-9889-4290-b90a-5e9f86682449&pf_rd_r=F8VB199KBC9QMSW73GQ1&psc=1&refRID=F8VB199KBC9QMSW73GQ1)
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.


![](https://paper-attachments.dropbox.com/s_B23788B5B4D37FD8498C15BC46E151D1AD791B8685401758D37455E7741B972B_1572601341330_Group+2+1.png)


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:

```bash
npm install -g t2-cli
```

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:


![](https://paper-attachments.dropbox.com/s_B23788B5B4D37FD8498C15BC46E151D1AD791B8685401758D37455E7741B972B_1572630626754_image.png)


It takes [30 seconds](https://github.com/tessel/t2-firmware/issues/117) 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:

```bash
t2 list
```

You should see a message like the one below:

```bash
INFO Searching for nearby Tessels...
  USB Tessel-AF768F095
```

`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:

```bash
t2 rename <name>
```

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

```bash
INFO Searching for nearby Tessels...
  USB HomeFan
```

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

```bash
t2 wifi -n <network-name> -p <password>
```

- `<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:

```bash
t2 provision
```

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

```bash
INFO Searching for nearby Tessels...
        HomeFan        LAN
        HomeFan        USB
```

## 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](https://paper-attachments.dropbox.com/s_B23788B5B4D37FD8498C15BC46E151D1AD791B8685401758D37455E7741B972B_1572450701734_image.png)


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](https://paper-attachments.dropbox.com/s_B23788B5B4D37FD8498C15BC46E151D1AD791B8685401758D37455E7741B972B_1572457589238_image.png)


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](https://paper-attachments.dropbox.com/s_B23788B5B4D37FD8498C15BC46E151D1AD791B8685401758D37455E7741B972B_1572457832335_image.png)


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](https://paper-attachments.dropbox.com/s_B23788B5B4D37FD8498C15BC46E151D1AD791B8685401758D37455E7741B972B_1572458280902_image.png)


**Relay ←→ Fan**

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


![](https://paper-attachments.dropbox.com/s_B23788B5B4D37FD8498C15BC46E151D1AD791B8685401758D37455E7741B972B_1572522175124_image.png)





## 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

```bash
t2 init && mkdir public
```

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:

```bash
npm install --save express body-parser socket.io tessel tessel-gpio-relay
```

**A node server**

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

```js
// 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!',
  );
});
```


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:

```html    
<!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>
```    

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:

```js
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);
    });
  });
});
```

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:

```bash
t2 wifi
```

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
```

Copy the IP address, then run the following:

```bash
t2 run server.js
```

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.


![](https://paper-attachments.dropbox.com/s_B23788B5B4D37FD8498C15BC46E151D1AD791B8685401758D37455E7741B972B_1572593598511_image.png)

## 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](https://docs.microsoft.com/en-us/azure/iot-hub/quickstart-control-device-node?WT.mc_id=devto-blog-chnwamba) to connect your device to IoT hub and control it from a cloud.

You can also use [temperature sensors](https://www.sparkfun.com/products/13676) 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](https://docs.microsoft.com/en-us/learn/modules/develop-test-deploy-azure-functions-with-visual-studio/index?WT.mc_id=devto-blog-chnwamba) on serverless functions.