Introduction: Automated Windows Shades

About: I'm an electronics enthusiast, passionate about science, and programming. Building things from scratch makes my day! If you like my work, you can help me https://www.buymeacoffee.com/danionescu

A word ahead

I've seen a lot of tutorials on how to automate manual shades and blinds, well in this one we'll automate electric shades. We'll cover electric shades ran by continuous current (DC) electric motors that open or close by reversing the polarity of the current.

Although if you buy electric shades you'll get some automation there are reason for doing the automation on your own like:

* you may have only a switch near them for up/down control

* it's cheaper (some companies offer advanced automation for a lot of extra $$)

* more flexible, you can program them do open or close on various circumstances, we'll learn about making a webserver in python that will connect to the shades bluetooth interface, and expose an API to control the shades, we'll also be integrating it with thingspeak and there you could do things like control the shades on a time schedule or control it via sensor input

This will be an intermediate tutorial, you'll need skills like soldering, arduino programming, basic electronic understanding, and some how to install services on a server, running and configuring them.

If you liked the youtube videos, you can subscribe here.

Step 1: Things Required

Tip: enlarge the pictures to view the descriptive labels on them

Parts:

1. arduino pro mini 16Mhz 5V type (eBay) 2$

2. HC-05 bluetooth module (eBay) 3.3$

3. 5 V Two channel relays (eBay) 1.6$

4. NPN tranzistor that is rated for at least a few amps, i've used Tip142T < 1$

5. 220 ohms, 0.25W rezistor <1$

6. diode, 1N4004 <1$

7. wires to connect the parts < 1$

8. PCB (eBay) <1$ per piece

9. 2 x KF301-2P plug in screw connector (eBay) <1$ per piece

10. male-female jumper wires (eBay) 1.2$ x 2 for a bunch

11. L7805CV 5V regulator (eBay) < 1$ per piece

12. 5.5mm DC Power Plug Jack Socket male and female (eBay) < 1$ per piece

13. Heat Shrink Tubing or insulating tape

14. Power supply, the supply must be rated for 12V and 2-3A.

I've salvaged mine from a 12 V 2 A charger (eBay) 3.2 $

14. Terminal strip block (eBay) 15c

15. fuse holder (Aliexpress) 1$ per piece

16. fuse (eBay) < 1$ per piece

17. male&female pcb connectors (eBay) < 1$ for what we need

18. AC power cable

19. plastic box enclosure, mine was 6 x 19 cm


Tools:

1. Soldering iron with solder

2. Wire cutter

3. Various screwdrivers

4. Cutter

5. power drill and 8.5 mm drill bit

6. USB to serial FTDI adapter FT232RL to programm the arduino pro mini

7. Laptop with ArduinoIDE installed to program the arduino

8. Lighter if you use Heat Shrink Tubing

9. A smartphone capable of bluetooth connection ( i use an android in the example ) with a bluetooth software installed

10. Optional: magnifying glass, multimeter, pliers

Step 2: Preparations

Choosing the power supply, and the plastic box

First thing is to determine how much current and what voltage do the shades motors operate.

This can be done reading the specifications or taking measurements using the multimeter. Usually they operate 12 V and 1-3 Amps (mine are 2.5 A and 12 V). Multiply the current by how many of them do you need to drive simultaneously (i drive two) to find out the maximum current needed. You should find a power supply that is exactly the same voltage and ideally the same amperage or slightly higher.

At this step i've cheated a little, using a 12 V and 2.5 A power supply to drive two 12 V and 2.5 A motors that means the motors use twice as much power as the power supply can give. But using a technique called PWM (check the link to see more details) i've managed to drive the motor simultaneously at a lower speed.

The reason i've did this is to save space in the box (i've chosen a smaller box).

The plastic enclosure will need to house the power supply, two relays, a small pcb with the electronics and wires so choose the size so that everything fits in.

My power supply had a plastic enclosure that i've ripped apart using a dremel tool, i've cut the existing wires and in this way i've got a cheap and small power supply suited for my project (see pictures).

Prepare the motor cables

You need to calculate how long the motor cables will be, that is until they reach the control box that we're buliding. Chances are that the existing cables are not long enough, and you'll need to extend them, strip both wires (the existing blades cable and the extension cables) at one end, put heat shrink tubes , solder the wires then apply heat with a lighter to insulate.

At the end of the extension cable there will be a male 5.5mm DC Power Plug Jack Socket. You need to solder the two wires to the socket the final result will be like in the pictures.

Inserting the female 5.5mm DC Power Plug Jack into the box

Using the drilling machine drill two holes large enough for the jack to slide through. Insert the power plug jacks in, screw using the nuts. Then solder thick black and red wires to each of the jacks input, after that insulate them using heat shrink tube. The wires should be long enough to go into the terminal strip block easily, but not to long to occupy too much space.

Attaching the fuse holder with the fuse

To one side of the box drill a small hole to put a small nut that holds in place the fuse holder. Then using the pliers, a screw driver and the nut, screw it tight into position. The fuse holder should be near the power supply location, and should be inside the box. Once again check the pictures.

Step 3: Building the PCB With Electronics

The PCB will hold the microcontroller, the bluetooth communication, the RTC module, a power tranzistor with a diode for protection and a small rezistor, connectors wires and a 5V regulator.

I've attached the fritzig schematic so things will be easy. The first picture represents the exported image of the schematic and i've also attached sketch.fzz (the original file, you can open it with this tool)

Soldering steps:

1. cut the female PCB connectors, there are two 12 pin connectors for the microcontroller, there is also a 6 pin connector for the bluetooth and a another 12 pin connectors on the right side of the microcontroller and a two pin connector for the relay negative and positive power

2. After all the connectors are cut there must be soldered on the back of the PCB

3. Solder the two KF301-2P plug connectors

4. Put L7805CV 5V regulator on the PCB. Bend it's legs and solder it on the other side then cut the excess legs with the cable cutter

5. Solder the NPN Tip142T tranzistor and the 1N4004 protection diode, cut the excess legs after

6. Solder the 220 ohm rezistor between the corresponding digital pin 5 and the tranzistor base pin

7. Solder thicker wires between the tranzistor and the KF301-2P plugs (red and black as they are marked on the pictures)

8. Solder all the red(+), black(-), and white(signal) thin wires according to the fritzig schematic

9. Solder male pins on the microcontroler you need two 12 male pins on the sides

10. Make connections between each of the microcontroller right side female corresponding pins (it's explained better in the pictures). The connections will be made using just solder (the pins will be close)

11. Optional: with the magnifying glass inspect the solderings for short circuits, and check if the wires are properly soldered on the back of the PCB, also you can check with the multimeter (resistance setting) if there is a short circuit between positive and negative connections. Another test is to power the circuit without the microcontroller, bluetooth

12. Place the microcontroller and the HC-05 bluetooth on the pcb

Step 4: Wiring and Assembly

   By now we have our pcb ready, our plastic box ready the shades cables wired up, and our other components prepared. All we need to do now is wire the system.

1. through the upper side hole in the box insert the AC power cable, strip the cable and solder it on the power supply (if your power supply has screws then screw it)

2. using a red wire solder the output(+) of the power supply to one of the fuses side, use a bit of heat shrink tubing to hide the exposed stripped wire.

3. solder another red wire to the other side of the fuse apply shrink tube, the other side of the wire should be inserted and screwed into the input (+) of the KF301-2P screw connector

4. solder a black wire to the output (-) side of the power supply and then screw it on the PCB input KF301-2P screw connector

4. Using male-female breadboard connectors, connect the relay positive and negative to the pcb positive and negative female connectors. Also connect pins 8 and 9 of the microcontroller (using the pcb mother connectors to the left of the PCB) to the relay trigger pins

5. connect one side of the terminal strip block to the red respectively black wires coming from the female 5.5mm DC Power Plug connectors. In you have more then one 5.5 mm female connectors like i do, then all of the red wires will end up in the upper left side of the terminal block, and all the black wires on the upper right side of the terminal block (see pictures). When you'll operate the shades if they don't move in the same direction we'll reverse the wires here (more on that later)

6. connect the positive and negative wires coming from the KF301-2P (out) screw connector to the middles of the relay terminals. The middle of the terminals are called common.

7. connect the left side of the left relay (does't matter how you're facing the realy) to the left side of the right relay to the lower left side of the terminal block. Then connect the right side of the left relay to the right side of the right relay to the lower right side of the terminal block. The terminal block will have the upper side connected to the female 5.5 mm connectors (see step 5).

Note: I've described the terminal block as having a upper and lower sides each having a left and right side. It doesn't matter how you hold the terminal block as long as you remember what side is what. You can check the pictures and especially the fritzig schematic.

Step 5: The Arduino Code

The code needs to be uploaded to the arduino pro mini using the USB to serial FTDI adapter FT232RL.

You will need to connect the GND, VCC, Rx, Tx and DTR pin to the arduino pro mini. Then open the arduino software select tools/port and whatever port you're using. Then Tools/Board/Arduino Pro or Pro Mini. Then Tools/Board/Processor/ATmega328(5V 16Mhz).

Finally, open the sketch below, and press upload.

Adjustments: The only thing that can be adjusted in the sketch is the pwmPower. The value can be between 0 and 255 and it roughly represents how much of the power supply power will go to the shades motors. It's basically switching the power rapidly on and off. I've implemented it mostly to allow me to use a smaller power supply without overheating or shutting down. If your power supply has a greater power than the motors will draw you can set the pwmPower to 255.

So how does this program works: first it listens to the serial line (a secondary software serial) for incoming transmissions. When a transmission arrives, the message is read in a buffer until the ";" is present or the end of buffer is reached. Then it's parsed and if it's in correct format (ex: O45;) the function toggleState is called with the first parameter state, and then the duration.

To achieve the polarity switch both relays are either opened or closed. The tranzistor is switched on and off using the PWM for the specified duration. O45 will mean open for 45 seconds.

After the command is executed, the buffer is cleared.

Step 6: Usage

We can use the controls in more than one way

1. Via an android or iphone bluetooth application (simplest)

In my demo i've chosen an android app called Bluetooth Controller.
This app let's you customize buttons that will send serial data. I've created two buttons called Up and Down, i've associated Up with the code "C40;" and the Down with "O35;".

"C40;" means that i'll close (retract) the shades for 40 seconds, "035" means that 'll open (they go up) for 35 seconds. ";" is the command terminator i've chosen in my sketch, that means that it signals the end of a command.


2. Via a python script that is running continuously in the background

This is the advaced part of the tutorial. I have mande a python script that will run on a server like a raspberry pi or laptop with internet access. It will connect to the bluetooth on the control box, and it will expose a http API. The API can be accessed directly or through thingspeak.

I'll explain step by step what will you need to do

a. first thing is to pair the bluetooth

you will be using bluetoothctl command from console, inside type

     power on
     discoverable on
     agent on
     default-agent
     pairable on
     scan on
     pair xx:xx:xx:xx:xx:xx (and enter password)
     trust xx:xx:xx:xx:xx:xx   (if no password):</p>

next open the bluetooth configuration file

vim /etc/bluetooth/rfcomm.conf

inside you will need to configure your bluetooth device like so:

rfcomm1 {

        bind yes;

	device your_bluetooth_mac_address something like 97:D3:31:21:A0:51;

        channel 1;

	comment "Connection to my shades bt";
}

bind, restart the bluetooth services

<p>sudo rfcomm bind all<br>sudo /etc/init.d/bluetooth restart
sudo hciconfig hci0 up</p>

b. install flask, flask basic auth:

sudo -H pip install Flask  Flask-BasicAuth

c. create a file server.py with the following code and run the server:

# usage: python httpToBluetooth username password bluetooth_address

# Note: username, password are used</p><p>import os, bluetooth, sys, threading


from flask import Flask
from flask_basicauth import BasicAuth
from queue import Queue

app = Flask(__name__)
configuration = sys.argv
app.config['BASIC_AUTH_USERNAME'] = configuration[1]
app.config['BASIC_AUTH_PASSWORD'] = configuration[2]
queue = Queue()
basic_auth = BasicAuth(app)

class BluetoothBackground(threading.Thread):
    def __init__(self, bluetooth_address, queue):
        threading.Thread.__init__(self)
        self.__bluetooth_address = bluetooth_address
        self.__queue = queue
        self.shutdown = False

    def run (self):
        self.__bluetooth = self.get_bluetooth()
        while not self.shutdown:
            message = self.__queue.get()
            self.__bluetooth.send(message)
        self.__bluetooth.close()

    def get_bluetooth(self):
        connection = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        connection.settimeout(None)
        try:
            connection.connect((self.__bluetooth_address, 1))
        except Exception, e:
            print 'Error connection to bluetooth' + str(e)
        connection.setblocking(False)

        return connection

class Webserver(threading.Thread):
    def run(self):
        port = int(os.environ.get('PORT', 5000))
        app.run(host='0.0.0.0', port=port, debug=True, use_reloader=False)

    @app.route("/send_to_serial/")
    @basic_auth.required
    def send_to_serial(command):
        queue.put(command)
        return 'ok'

threads = []
threads.append(BluetoothBackground(configuration[3], queue))
threads.append(Webserver())

[thread.start() for thread in threads]</p>

to run the server execute:

python server.py user password 97:D2:31:20:A0:51

Ok, so server.py is our script, user and password are the credentials used for your authentication, and "97:D2:31:20:A0:51" is your bluetooth MAC address.

d. use your server to send commands from anywhere in the world

from the browser type : http://your_ip:5000/send_to_serial/C30;

- enter the user and password that you've set up earlier when started the python server

- "C30;" is the command that will be forwarded to the bluetooth device (our box that will controll the shades)

- check that port 5000 is not blocked by your firewall (we're using that port)

- if you're behind a router (for example a raspberry pi) you need to make a port forwarding from the router from port 5000 to port 5000

e. you can use thingspeakto do things like controlling the shades on a time schedule or when some channel sensor data changes. For example you could hook a light sensor(outside) to thinkspeak and when the light level drops to some amount (it's evening) you can close the shades so that people outside don't see you.

You can connect the shades (python server we've set up earlier) with thingspeak using ThingHTTP.

I've included a picture of ThingHTTP form with the data filled in as an example and a picture with TimeControl So for maximum flexibility thingspeak should do whatever you need.

3. Via my home-automation application

This is a bit more complicated, my home-automation application does a lot more than controlling the shades.

It also controls lights, the door, has multiple sensors, integrates with switches and has complex user defined rules that can for example open the shades if the light level inside is low, or if it's morning.

You can check my github repository, and if you have questions i'll be happy to answer them.

If you found my tutorial somewhat useful please share it or add it to favorites. And i want to see some interesting comments too :)

Arduino Contest 2016

Participated in the
Arduino Contest 2016