Thursday, September 1, 2016

ESP Relayserver

So I was busy with a project and things would not work out as I wanted. The hardware was Ok but I had some serious problems concerning the software for the ESP8266 written in LUA. To take my mind of the problem I decided to start another project.




What I wanted was an easy way to switch a relay on or off over the internet. Now this is something that already has been done a load of times, however I wanted to incorporate something that is so obvious, but I never saw it done before.

I wanted the realy to have a manual override.

What´s the reason for that. Well imagine you have a relay that you can switch on and off over the internet and you switch a lamp with it. That is obviously nice but how about you switching it on remotely while the people at home do not want that. Well they can of course pull the mains plug out. But that´s not convenient and you who are at a remote place then will not now that the lamp is out. So I wanted not only a manual override but also a feedback to the internet about the state of the lamp. And that really is not something I have seen in someone elses project before.

It really turned out very simple.

The relay.




Modern relays can be bought for, at the time of this writing, way below 1 dollar or euro. Best part is that they have everything on board for working with a micro-controller. They have a power-led and a led that shows wether the relay is active or not. Next to that they incorporate a power transistor and all electronics further needed. So the only thing you need to supply is power and a digital on or off signal.

If you have some old relays in stock you can still read on. You just have to make your own relay controller and that's not so difficult either. Just follow the guide I wrote in this story, and attach the base of the transitor to the ESP8266 which we are going to use.

Power supply

As this is going to be a stand-alone project it needs a power supply. I used an USB mains adapter for this as, how convenient, it has an USB connection with which we can feed the NodeMCU board and relay we are going to use in this project.




BEWARE
WE ARE GOING TO WORK WITH MAINS CONNECTIONS HERE AND THEY ARE REALLY HAZARDOUS. PLEASE STAY AWAY FROM THE MAINS ADAPTER IF YOU DO NOT KNOW WHAT YOU ARE DOING AND ARE NOT AWARE OF THE DANGERS INVOLVED.
I ACCEPT NO LIABILITY OR RESPONSABILITY FOR YOU FOLLOWING THIS PROJECT AND GETTING INJURED/KILLED  OR HAVING YOUR HOUSE BURNED DOWN OR WHATEVER DAMAGE MAY RESULT FROM FOLLOWING THESE BUILD INSTRUCTIONS OR YOUR OWN VARIATIONS OF IT.

Before making any alterations to the adapter make shure it is not plugged in the mains !!!




First I started with taking the USB mains adapter apart. As you can see it is a perfect fit in the small housing.




If you remove the print out of the housing you can see two leads (red and black) going to the mains connection. Cut these loose. We now have the print seperated from the housing and that is what we need for our project.

Mains cable.

Before proceeding make sure the mains-cable is unplugged !!!



You will need a mains cable with a plug on one side and a contra plug on the other side. The plug will go into the mains outlet in the wall and your lamp (motor, pump or whatever) will be plugged into the contraplug.

Somewhere in the middle or whatever suit you best cut the wire and strip it. Put it in a screw terminal and on one side attach the black and red wire from the USB-Mains adapter so that will be powered. Now on the other side (this will be the side with the contra plug) a few inches away cut 1 wire of the mains cable and strip the ends. Feed the ends in the relay's terminal screws.

Wiring the ESP8266

I used a NodeMCU version of the ESP8266. This has the advantage that it is USB powered, can easily be programmed (directly over USB) and has many I/O pins.






I think the schematics and the breadboard layout tell it all.

I used two switches attached to D1 and D2. These are the MANUAL OVERRULE and MANUAL SELECT switch.
A led attached to a delimiting resistor is attached to D4 and that will give a visual feedback wether MANUAL OVERRIDE is switched on or off.
The Relay is attached to ground, 5 volts and to pin D3 of the NodeMCU which triggers it.
And that's all.

Casing



I wanted a nice casing for this so I started my (now favorite) design program 123D-Design. Lately I have been switching from Tinkercad to 123D-Design. 123D-Design has a few nice tricks up its sleeve and it works off-line which seems to be a bit faster as Tinkercad. I can save all my files locally and am not depended on the quirks of a slow, bad or busy internet connection. 123D-design is now part of the 123D family which is owned by Autocad. So switching did not make me feel a traitor.

I made a casing which has 3 distinct compartiments. One for the mains-part, one for the realy, and one for the electronics. On the side of the casing I made holes for switches and the led.

The Led is places next to the MANUAL-OVERRIDE switch. The On-Off switch is put a bit further away.



And At last a fitting lid was made.


Putting it all together.



As you can see I drilled two holes trough which the mains cable enters the housing.
On the left side of the casing is the power supply, attached with a normal USB-cable to the NodeMCU on the right side. In the middle is the relay.
I Put the NodeMCU on a stripboard which makes it easy to get it out of the casing if I want to alter the software in the future.


For safety I glued all the components to the casing using a hot-glue gun. I also taped down the contacts on the switches for preventing any short circuit.


The software

The software is written in LUA. The download link is at the bottom of this page, you can however also copy and paste it from the next listing.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
wifi.setmode(wifi.STATION)
wifi.sta.config("MYROUTERNAME","PASSWORD")
print(wifi.sta.getip())
relay = 3
relaystate = 0
switch1 = 2
manual =1
led = 4
gpio.mode(led, gpio.OUTPUT)
gpio.write(led,gpio.LOW);
gpio.mode(relay, gpio.OUTPUT)
gpio.write(relay, gpio.HIGH);
relaystate=0
gpio.mode(switch1, gpio.INPUT, gpio.PULLUP);
gpio.mode(manual, gpio.INPUT, gpio.PULLUP);
srv=net.createServer(net.TCP)

tmr.alarm(1, 1000, 1, function()
if (gpio.read(manual) == 0) then
    gpio.write(led,gpio.HIGH);
    print (gpio.read(switch1))
    if (gpio.read(switch1) == 0) then
    gpio.write(relay,gpio.LOW);
    relaystate=1
    elseif (gpio.read(switch1) == 1) then
    gpio.write(relay,gpio.HIGH);
    relaystate=0
    end
end
if (gpio.read(manual) == 1) then
gpio.write(led,gpio.LOW);
end
end)



srv:listen(80,function(conn)
    conn:on("receive", function(client,request)
        local buf = "";
        local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
        if(method == nil)then
            _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
        end
        local _GET = {}
        if (vars ~= nil)then
            for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
                _GET[k] = v
            end
        end
        buf = buf..'<head><meta http-equiv="refresh" content="20" /></head>'
        buf = buf.."<h1> ESP8266 Relay Switch</h1>";
        buf = buf.."<h1> Luc Volders 2016</h1>";
        if (gpio.read(manual) == 0) then
            buf = buf.."<br/>";
            buf = buf.."Manual override = ON"
            buf = buf.."<br/><br/>";
        elseif (gpio.read(manual) == 1) then
            buf = buf.."<br/>";
            buf = buf.."Manual override = OFF"
            buf = buf.."<br/><br/>";
        end
            if (gpio.read(switch1) == 0) then
                buf = buf.."Manual Switch = ON";
            elseif (gpio.read(switch1) == 1) then
                buf = buf.."Manual Switch = OFF";
            end
            buf = buf.."<br/>";
            if (relaystate == 1) then
                buf = buf.."Relay is ON";
            elseif (relaystate == 0) then   
                buf = buf.."Relay is OFF";
            end 
            buf = buf.."<br/><br/>";    
        --end
        buf = buf.."<p>GPIO0 <a href=\"?pin=ON1\"><button>ON</button></a>&nbsp;<a href=\"?pin=OFF1\"><button>OFF</button></a></p>";
        local _on,_off = "",""
        if (gpio.read(manual) == 1) then
            if(_GET.pin == "ON1")then
                gpio.write(relay, gpio.LOW);
                relaystate=1
            elseif(_GET.pin == "OFF1")then
                gpio.write(relay, gpio.HIGH); 
                relaystate=0    
            end
        end    
        client:send(buf);
        client:close();
        collectgarbage();
    end)
end)

Make sure you put the right information in line 2 substituing MYROUTERNAME and PASSWORD with your router info.
The next lines do the setup by defining the I/O ports as input or output and giving the variables the right initial values.

In line 18 the timer function constantly checks wether thw Manual-Override button has been pressed. If it is the led is put on otherwise the led is switched off. Next the routine tests the switch button which puts the relay on or off.

From line 37 onwards the web-page is defined and build.
In line 50 I use a trick I have used before. I put a refresh statement on the page wich makes sure the page is refreshed every 20 seconds. You may alter this to your liking by altering the figure 20 which sets the seconds before refreshing.

Lines 53 to 61 test wether the MANUAl-OVERRIDE is on or off and displays that information on the web-page.

Lines 62 to 73 test the state of the switch and tests the variable relaystate that holds info about the relaystate (duh) and display that info on the webpage.

The last lines detect what button you press on the webpage (on or off) and act accordingly by putting the relay on or off.

Wow !!! A complete relay commander on a webpage with actual feedback on the state of the buttons in just 90 lines of code !!!!!

As my web-page says GPIO0 you might alter the text in line 75 in "Put the Relay" or something to your liking.

Actually I urge you to alter the text in this program anyhow. That will give you more feeling in LUA programming.

You could also alter the entire program in switching more relays. As we have pins D5, D6, D7 and D8 unused you could add another 4 relays or 2 relays and 2 control leds. This would have you change the casing also which is also a good exercise in working with CAD/CAM programs.

Putting it to work.

First put the mains plug in a mains wall-socket and wait a few seconds. 

Then open the configuration screen of your network router in your browser. Now look at the screen that shows you all connected devices.



In the above screen you can see that there are several wired devices attached : my computer, my Buffalo NAS and my Raspberry Printerserver with an Epson printer connected. Above these you can see an unknow device. That'll be the ESP8266 relayserver.



If I click on - Unknown - the router reveals the IP number.

Now put this IP number in your browser and instantly the webpage will be presented.



First push the MANUAL-OVERRIDE on the casing and you will see the text on the screen alter after a while (max 20 seconds which is the refresh rate of the screen discussed in the software). If MANUAL-OVERRIDE is on you can put the relay on or off with the switch on the casing. If MANUAL-OVERRIDE is on you can push the on-and off buttons on the webpage but nothing will happen.

If MANUAL-OVERRIDE is off the switch on the casing will not work and you can put the relay on or off with the buttons on the web-page.


Please be aware that if you switch the relayserver totally off (by unplugging the mains) the next time you start it it may get another IP number unless you give it a fixed IP number (you can do that in your Router's menu).That is what happened in my case so the IP number in the router-screen above is different as the IP number I used to call the web-page as the pictures were taken on a later date.

In real-life.




It works like a charm and is easy to use. The manual-override is a logical, nice and handy touch. And to be frank I am pleased with the casing and the complete design. It is a fun project which is simple to build and does not take a lot of time except for the printing of the case which took a few hours.

I can access the webpage from my computer, my phone and my tablet and as I opened a port on my router I can switch the relay on or off from any place in the world.

Just one word: NEAT !!!

Source codes.

As you know I am a grat fan of open-source software. Therefore as always all software and schematics are free to use and modify. Even the STL files for the casing are open. You can find all the sources on my Github repositry.

https://github.com/Lucvolders/ESP-Relayserver

So till next time
Have fun

Luc Volders

Monday, August 1, 2016

Rain sensor using ESP8266

Well here is my second project using the ESP-8266.

I already wrote a few stories about this small wonderboard. The previous real project which you can read by clicking here was about controlling a ledstrip over wifi.

Previous stories I wrote about the ESP-8266 were about making a programming board for the ESP-8266-01. The small board with just 2 I/O pins. And you will need this programming board as I am going to use that same ESP-8266 version here again. You can find the instructions for making the programming board here.
The second story was about flashing the right firmware on the ESP-8266. And you really want to be up to date with the latest firmware so you are going to need that storry to. You can find it here.

This story is going to be different. It is going to be my second real complete project using the ESP-8266.

In my last blog entry I showed you that I tested some of my 3D prints to prove wether they were water proof. In this article I mentioned that I was going to do a project that involves bringing the electronics outdoors. Well here it is.


So what is it going to be. It is a rain detection system that sends notice over wifi to your computer/laptop/tablet or phone if it is raining. The project is not just a practice for building something with the ESP but it really is practical too. My girlfriend and I are in some ways old-fashioned. So when she has done the laundry she puts it outside to dry. And sometimes we are not paying attention and it starts to rain. That's why I wanted a sensor that would inform me that it started to rain.

Water level meter / Rain detector

I bought for a few dollarcent a water level meter/rain detector.




It is a small board with long strips of cupper-leads and 3 connections power (+), gnd (-) and Signal (s). As it did not have any documentation accompanying it I had to do some research myself.

Before attaching it to my ESP-board I hooked it up to a power supply (3 AA batteries) and my multimeter. The setup was the following. The power and ground were connected to the battery case. The ground was also connected to my multimeter and the signal line was also connected to my multimeter. Then I started doing some tests.





First I measured resistance.
When the board was dry I measured 105 Ohm. When humidified with a wet finger I measured 1 mega Ohm. This could surely be usable if the ESP8266-01 had an analogue input. But it hasn't. It's larger brother the ESP8266-12 does have an analogue input just like the fantastic NodeMCU board. But using these would be overkill for this project.






So next I measured voltage.
The dry board gave me 0.03 volt. And when I humidified the board again with a wet finger I measured 2.68 volt. Now we are getiing somewhere.

So when the board is dry it gives a LOW or 0 signal. And when it is wet it will give a HIGH or 1 signal. That is usable.

Connecting the ESP to the Rain detector.

Well this is straightforward.

For testing purposes I used my programming board. At the end of my board is a header in which I can put breadboard cables. So I plugged in a cable for the power, ground and on the GPIO2.

These cables were then connected to the water level sensor/rain detector. That's all. At least I thought it was.

When I started testing this I noticed two things.
- The signal the rainmeter was giving was not quite strong enough to trigger the ESP
- When using AAA batteries they were drained too fast.

Lets tackle the first problem.

The signal the rain meter was sending to the ESP was too weak. So the ESP would not be triggered if it started to rain.

First I wondered why this would be. But then it occurred to met that this was not only a rain meter it was also a water level meter. The signal would get stronger as it was submerged more into the water. This would not be a problem if I would attach the rain sensor to an analogue pin. However I did not have an analogue pin on my ESP8266-01. And I was not really interested in the water level. So I had to make the sensor work as a switch. As soon as a drop of water would fall onto the sensor it would have to give a signal to the ESP8266.

Piece of cake. I would feed the sensor output to a transistor who would amplify the signal. Then it would trigger the ESP8266.

Well not exactly a piece of cake. I was at first trying to get this working with 2 AA batteries. However this did not work. The currect was to low and the voltage would drop too much. So I decided to try some really bad design practice. I would feed the project with 5 volt for testing purposes and with 3 AA batteries in the field. And indeed that worked like a charm.

Now this is bad practice as the ESP works on 3.3 volts and not on 5 volts. However it works and that is what really matters to me. Two AA batteries were just to weak. Use this at your own risk. If you want to play safe add a voltage step-down circuit as described in the led controller story (click here).


Last minute update. At the time I am writing this there is a discussion going on on Hackaday wether the ESP is 5 volt tolerant. And there was a comment from Espressif on Twitter that confirmed that the ESP I/O pins are indeed 5 volt tolerant. You can find that communique at 
https://twitter.com/esp8266com and look at the 30 july entry from Teo Swee AnnSo if you want to play on the safe side you could attacht 5 volts to the rain meter and pick up the 3Volt current from two of the batteries for the ESP. 
However I am not going down that road and use the 3 battery setup as it works fine in my case. Again: do not blame me if it blows your ESP.







So look again at the breadboard layout and schematics. I put a 68ohm resistor between the rain-sensor and the base of the BC547 and I limited the current with a 1 kilo-ohm resistor. This has been working for several weeks now without any problems.

STA or AP

On to the software. There were two possibillities. I could make a stand-alone network server for this putting the ESP8266 in AP (Acces Point) mode. This way it would not take an IP number on my router. However it would be impossible then to access the ESP8266 from my desktop system. It would be accessible over wifi from my tablet or phone. Then again the tablet or phone should be dedicated-connected to the ESP8266 and could not access the internet at the same time.

I decided to put the ESP in STA (station mode). That way it would be connected to my router. It could be accessed (if I wanted) from anywhere in the world so not only when I was home. And I can access it from any device in my home network being my desktop computer, any of my raspberries, my tablet(s) or phone(s). For now that seamed the best option. In the long term I want to make the rain-maker part of my home-automation system. I need to reprogram the ESP for that and that is why I did not solder it to my strip-board but put it on headers.

Programming the ESP8266

First start with flashing the ESP8266 with the latest firmware. You can find my stories about the programming board and flashing the firmware by clicking here and here.

Next step is to load the LUA program in Esplorer and flash it into the ESP8266.

sensor = 4 -- GPIO2
gpio.mode(sensor, gpio.INPUT, gpio.PULLDOWN)
wifi.setmode(wifi.STATION);
wifi.sta.config("MYROUTER","ROUTERPASSWORD")
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)

    conn:on("receive", function(client,request)
   
        local buf = "";
        buf = buf..'<head><meta http-equiv="refresh" content="20" /></head>'
        buf = buf.."<h1> ESP8266 Rain detector</h1>";
        buf = buf.."<h1> Copyright Luc Volders 2016</h1>";
        if(gpio.read(sensor)==0)then    
        buf = buf..'<h1><span style="color:red">It rains !!!!!</span></h1>';
        end
        client:send(buf);
        client:close();
        collectgarbage();
    end)
end)


Test it and make sure it really works like you expect.




Then go to the right side of  the Esplorer screen. Click on reload and a list of all programs in the ESP's memory is displayed. Left click on regensta.lua and rename it in init.lua. This way the program will automatically start when the ESP gets power.

And this is all. A complete web-server and rain-checker in just 21 program lines. The ESP-8266 is truly a wonderboard.

The program is mostly straightforward except some points I would like to bring to your attention.

gpio.mode(sensor, gpio.INPUT, gpio.PULLDOWN)

This line sets the GPIO pin as an input pin and makes sure it is pulled down. This makes sure that the input normally is at 0 (ground) level. It only becomes 1 (HIGH) when it is actually raining.

buf = buf..'<head><meta http-equiv="refresh" content="20" /></head>'

This line is especially interesting.
Normally your webpage is static. It only refreshes when you actually re-enter the ip-adress of the page. that is not a really handy feature as we would need to refresh the page regularly manually to check if it is raining. Now this particular program line makes the page refresh automatically every 20 seconds. And that is what we really want.

This way I open a small browser window in which I have this  webpage open all the time. This webpage sits somewhere on my computerscreen and I can get an automatic update every 20 seconds about the weather condition. And if I am not at my computer I can check it on my phone or tablet.

Where to find the webpage.

First open the configuration screen of your network router in your browser. Now look at the screen that shows you all connected devices.



In the above screen you can see that there are several wired devices attached : my computer, my Buffalo NAS and my Raspberry Printerserver with an Epson printer connected. Above these you can see an unknow device. That'll be the ESP8266. It's IP number on my router is 192.168.1.75.



So when I enter that IP number in my browser I will be presented with the ESP8266's webpage.



And when it rains TADA !!!!

As you can see in the picture above several tests and resetting the ESP-8266 did make the IP-Adress change.

How to use it.

When I am working at my computer I just open a browser window, enter the IP number and adjust the window so that only the the few lines of text are visible. If I need to surf the web I just open another browser window and adjust the size to what is needed to properly surf the web.
I can also open the rain-detectors webpage on my Android Phone and display the information there. That way I do not have to be at my computer to get the weather condition.

This works however is not really practical.
To make it more practical I am going to show you in an upcoming story how the ESP can send a Twitter message to my phone. This is then displayed on my Android's main screen which draws far more attention.

Casing

As the software will change in the future I know I am going to keep the hardware the same. So I made a casing for this project.



First about the interior. It is made by first arranging 3 battery holders in the position where I want them. This way I have a space in the centre where the hardware fits in. You can find the individual files and description for the battery holder by clicking here.

As you can see I am using bended paperclips as battery contacts. This works as a charm.



The above picture shows you how all the circuitry fits in.



And here is the closed case, ready for the great outdoors.

This will run approximately a day on 3 AA batteries which is more as enough for getting the laundry dry.

For those of you that are eager to make one of these yourself and have a 3D printer I will provide you with the STL files.

Rainsensor Case
Lid for Rainsensor Case

So till next time.
Have fun

Luc Volders

Thursday, July 14, 2016

Waterproofing your prints

I was making a project that involved electronics that need to be placed outside my house. Therefore I needed a waterproof housing. Buying a housing for my electronics is something I do not do anymore. After all I have a 3D printer.

So I needed to be sure that if I designed a housing and printed it myself that it was waterproof.

Last year I made a fence in my garden and I designed and printed caps for the wooden poles. You can find that story here. But electronics are far more delicate as wooden poles. So I really needed to be sure that my prints were waterproof.

And the proof of the pudding is in the eating.



So I designed first a AA battery case and next a box.





The box was printed with a 0.3mm layer hight and width and with 1mm thick walls. The bottom also was just 1 mm thick. As you can calculate for yourself the walls were therefore made of 3 layers.

The batterycase was something else. The walls are 3mm thick as there will be some force on the case. And this was also printed with a 0.3mm layer width and thickness.


I filled them up with water and put them in a large plastic box so no harm could be done if there was a leak.

Well I was pleasantly surprised.
After 3 days not any sign of a leak
That was enough proof for me as the project would never be so long outside.

What does it prove.
Well it proves that MY printer is capable of printing solid boxes that are waterproof as long as I use 0.3mm layer thickness and a box with a minimum of 1mm walls.
So as all my designs have a wall thickness of 3 solid layers I can be assured that my designs will be waterproof for several days.

Your mileage may vary so please do some tests for yourself before you put anything in the open.

Till next time

Luc Volders

Wednesday, June 1, 2016

Make your own IP cam with a Raspberry PI

This is going to be a lengthy post.........

I wanted to show my Ledstrip controlled by an ESP8266-01 to some of my friends. However as most of them have jobs like I do, and therefore not a lot of spare time. And some do not live next door. It is not easy to have them visiting me for just showing part of a project I am working on. 

I therefore needed a way to show them things without having them to visit me. And that is where an IP-Cam is the way to go. 
Skype could be a solution but then my computer always has to be standby and I have to be there to service it. With an IP cam they can just have a quick peek without me even being present. So having my computer permanent on for servicing a web-cam is out of the question. There should be another way. And there is.

The Raspberry PI

I have to admit it. I own several of them, but I don't tinker a lot with them. Too little time is what I have. I am talking about the famous Raspberry PI.


For those not familiar with the Raspberry PI I urge you to get to know it. It is a small Linux computer which has USB ports, an Ethernet port an Audio port and a HDMI port. You only add an SD card as memory a screen (HDMI or analog or even a tv) and a keyboard and mouse and you are set to go with a full fledged Linux computer. All this for about 40 euro. For more info look here: Raspberry Pi foundation.

So if I do not tinker with them why do I own several. Well one of these little gems is running Ponterface as the heart of my 3D printer system, another one is setup as a media player / game computer, one is  my inhouse printerserver and one is destined to be the heart of my domotic system.

And now I have set up a Raspberry as an IP-cam.

What is an IP-Cam

For those of you not familiar with the name I will give a small explanation.
Every one knows the ordinary web-cams. Most laptops have them build in nowadays and they are great for skype and other ways of communication.

They only have one small problem: they need your computer to operate. In comes the IP-Cam.

An IP cam is a webcam that is connected to a small computer and attached to your home network. You can buy dedicated IP cams that look as a small box. They indeed house a cam and a small dedicated computer. As they are attached to your home network you can access them from any computer, laptop, phone or tablet in your house. Hell you could use one as a dedicated door-bell. But they can also communicate through the internet with the whole world. So you can look at things in your house from any place in the world: from your work, during a holliday abroad etc etc etc. You can use them as surveillance cams, for following certain processes, trafic cam, bird cam or just to keep an eye on your wife.........

The setup

What I wanted to do is to make an IP-Cam with a Raspberry PI that did not need a mouse or keyboard attached. It does need a housing, a power supply, an SD card, an ethernet connection (to your network router or switch) and a USB webcam.

To program the Raspberry PI you do need a keyboard a mouse and a screen. But they will be removed later when all functions well. This means that the Raspberry will function standalone without a mouse, keyboard or screen. This is what we call headless.

The Start


First make sure you have a fresh Raspberry Pi setup with a fresh made Raspbian distribution. I am not going to tell you how to do that because there are plenty tutorials on that.


Installing the IP-Cam software.

Open in the Raspbian main screen your terminal screen and make sure you got the latest updates and upgrades by typing in the terminal screen:

sudo apt-get update
sudo apt-get upgrade

Now this may take a while so be patient. After the update and upgrade have finished we have to install the IP-Cam software. There are several programs suitable for this, but I'll be using Motion.
Motion is a lot more as just an IP-Cam. It can make snapshots and best of all it can detect.......motion. I will not be going into this last option at this stage as I am not using it for this project. So let's start with installing Motion.

sudo apt-install motion 

For the next step we need to edit the setup files of the Motion software. We'll do that by adressing the Nano editor. So still in your terminal screen give the following command:

sudo nano etc/motion/motion.conf

Now find (by scrolling or by using Ctrl-W) the following lines and edit them in the following (bold are the new values):
deamon on
webcam_localhost off
framerate 5

The last one is dependend on your network upload capabilities. My provider gives me a good download speed but a very low upload speed so I set it to 5. You might tweek it for your own purposes.

Dont forget to save the new settings.

One last part is to make sure that everytime the Raspberry is powered up the Motion software will start immediately we can do that by the following command, which you'll have to type in the terminal window:

sudo nano etc/default/motion

and find the following line and edit the value as follows

start_motion_daemon=yes

and that's it. The cam is installed. Now we can test it.

Testing the IP-Cam

Well first we need to know the IP adress where the cam is located on you network.In the terminal window type:

hostname -I

The Raspberry will promt you with it´s IP adress. It will be something like 192.168.1.75

This setup will use port 8081 on your Raspberry PI.

So now we know the ip-adress and the port it functions on we can have a look at what the cam sees.
In any computer on your network and even on the PI itself open a web-browser and put the following URL in:

192.168.1.75:8081

Remember to substitute the IP adress with the adress you found in the lines above.

That is it. You should see a picture of whatever the cam is aiming at. Updates will be a few frames per second depending on the afore mentioned settings.

You can now access your PI from any computer or laptop in you home network.

Fine Tuning

Ok this is fine. But everytime the PI starts it will start in graphical mode. That is fine for testing purposes but not needed for every day use.

So open your terminal program again and type the following line:

sudo raspi-config

And the original Raspberry configuration screen opens.
Now change the setting Enable boot to Desktop into boot to Console text.

The next time the PI boots it boots in console mode and does not have to load the graphical environment which will make it slightly faster.

So put the power off. Detach the mouse, keyboard and screen and reboot your PI. Wait a few minutes and open a web-page in another computer system. Use the IP adres mentioned above and you should see what the cam sees.

Connect to the world

This all works fine within the confinement of your won network. But we want to be able to see the webcam from anywhere in the world. So here are the next steps.

First lookup your own ip-adress. You can do that in your router or through a webiste like this:

 http://whatismyipaddress.com/

This site will immediately show your own IP-Adress. You can also find it in your router.

Best thing is anyhow to look it up in your router as you will need to alter the settings of your router anyway. Most likely you can access your router from your webbrowser by using the following IP adress: 192.168.1.1 If not consult the routers manual.

Your IP adress will be something like xxx.xxx.xxx.xxx being for sets of 3 figures.

We will need this -outide- ipadress in the future. But not now.

Now we need to setup your router for access from the outside world.

Look for the settings in your router that contol port-forwarding. In my router which is a Huawei it is found under the firewall settings. The external port we will be using on the router is 48461. We will re-route that port to Raspberry's IP-Adress which is 192.168.1.75 in my example and the port which is 8081. In my router it is done like the following picture shows:


Close the router and that's it.

Does it work ????

Well here is a screenshot. Beware that I am using el-cheapo webcam. I bought a few of them for 5 euro a piece so the quality is not the best. But it works.




And for those that are wondering what the hell it is I am showing. It is a Nodemcu. That is an ESP8266 devellopment board. I have attached it to the internet (just like my IP-Cam) and now it can be accessed from anywhere in the world. But that is another project..........

More finetuning

There are still a few things to do:
- When the Raspberry resets (by cutiing the power or whatever reason) it can get a new IP adress. So I need to give it a fixed IP adress in my network
- The port number 48461 is a bit difficult to remember so I need to set that in the Raspberry to something more easy to remember.
- Maybe I will use a free DNS service that will rename my IP-Adress for the outside world in something more easy to remember like lucswebcam.com or so.

All things that I can write about in future updates in thsi web-log.


So, till next time
have fun

Luc Volders




Sunday, May 1, 2016

ESP8266 Controlled Ledstrip

I needed a bit more light above my desk so I started looking around. My plan was to install a ledstrip that would be controllable over WIFI so I could eventually embed it in a domotics system. The easiest way is to use an ESP-8266 for that purpose.


At the dollar shop I found a nice led-strip which was battery powered. No controlling electronics, just an ordinary on/off switch to set the leds on or off. Battery powered means usable for many purposes and mobile. But that's not what I needed. However the ledstrip had an excellent price (3 euro) so I decided to buy it anyhow and give it a try. For just a few euro's you can't go wrong.






I started by testing the ledstrip with batteries. Before messing around with it I needed to be sure that it delivered enough light for my purpose. And yes indeed it was exactly what I sought. As you can see it delivers enough light for a small workspace.

On to the next step.
I wanted the ledstrip to be connected and controlled by an ESP-8266. However the ESP8266 can not supply enough current by itself to control the ledstrip. So I had to do some calculations.
There are 30 leds in the strip. As each led will consume about 20 mAmps the power consumption will be 30 x 20 mAmps is 600 mAmps. So a TIP120 transistor would be more as sufficient for the job. I build a test setup and examined if it would do the job.



As you can see a very simple setup. Just a TIP120 transistor that is attached to the 5 volt power reel and a loose breadboard cable (the green one) which I alternately plugged in the 5Volt and GND lines to see if the ledstrip would switch on. And that worked flawlessly. So the Tip120 was indeed the right choice.

Next step was to make the ESP-8266 do what I wanted.
And what did I want ???
Well I wanted easy access from a website.

I started with the hardware setup. I used a NodeMCU board for testing. The NodeMCU board gives breadboard access to all I/O pins and is easily programmable through its USB interface. The NodeMCU board is a miracle in itself however not really breadboard friendly. I could have used my NodeMCU breadboard aid which you can find by clicking here, but I decided to take the easy way out.


As you can see I only need the left side of the NodeMCU to get my prototype working so I just plugged it halfway into my breadboard. I attached 2 leds to GPIO0 and GPIO2.


Please note that the pinnumbering on the NodeMCU does not correspondent with the GPIO numbering. The pin called D3 is attached to GPIO0 and the pin D4 is attached to GPIO2.

The software


As you can see the software is pretty straightforward. It is written in the standard NodeMCU language: LUA

I chose for the Wifi-Station mode as this gives me access to the software from every computer, laptop, tablet and smartphone in my house, and if I open a port in my router from anywhere in the world.

Do not forget to fill in your own router details in program line 2 if you want to play with this webserver yourself.

Line 5 to 10 define the I/O ports and put them in the LOW state so the leds start in the OFF function.

Line 24 to 37 make the actual webpage. As you can see I just used 2 I/O ports so I made 2 ON-OFF switches on the webpage. You can easily expand this for your own purposes to use all I/O ports on the NoceMCU.

Just don't forget to rename this program in INIT.LUA if you want to start the webserver automatically when the NodeMCU is powered up.
And that is just what you need to do: power up the NodeMCU.

Next step is to get access to your router to see that IP adress the NodeMCU has gotten from your router. I can not tell you how to do this as each router works differently.




As you can see in my setup my router sees an unknown wireless apparatus that is attached. If I ask the details it shows the IP-Adress. This is the way to know how to adress your ESP module from inside your network.



Now if I type the just found IP-Number in my web-browser I will immediately get the above showed web-page. Isn't that just fantastic a complete web-page in about 50 lines program code !!! The ESP-8266 are really marvels.

Let's see if the software works.





Incredible !!! Fantastic. Just a few lines of code and I can switch led's on and off simultaneously from several devices (phone and computer) all accessing the same webpage. It is fully understandable why this ESP-module has so much attention in the tinkerer community.

And on we go to the next step.

Obviously I needed to combine the power transistor TIP-120 with the NodeMCU if I wanted to control the ledstrip over Wifi and here is the breadboard setup.




And there you go. Switching GPIO-0 on and off on the website really switches the ledstrip on and off.

Now there is one final thing to do.

It is a bit overkill to use a complete NodeMCU board for just controlling 1 GPIO pin. It is more efficient to use the tiny ESP-8266-01 for that. There are however a few things to take into consideration.

The ESP8266-01 does not have a USB port. Therefore you will need a FTDI for this. The easy way to achieve this is to build my ESP8266-01 Programming board which you can find by clicking here.

There is however antother small issue and that is that the ESP82636-01 baord works at 3.3 volt. As I was planning to power the complete setup from a 5Volt power adapter (the same one used as phone adapters) I needed to make a step-down power converter. And what is better suited for this as the LM317. You can find detailed information about this voltage regulator by clicking here.


In the story about the LM317 you will find a link to a calculator that gives you the right resistor values for stepping down from 5 volts to 3.3 volts. I used resistor values 1.2KOhm and 2Kohm. If you do not have them at hand you can substiture them (both) for values found by the calculator.




Above you can see the breadboard setup for the LM317 and the breadboard setup for the TIP120 and LM317 combined. There only rests one thing:



For completeness I included the total breadboard setup and schematics with the LM317, the TIP120 and the ESP8266-01. As you can see I used GPIO-0 for controlling the ledstrip.

There is just one small issue that needs to be taken in consideration.

For your convenience I give you the stripboard setup.
As you can see I added a switch between GPIO-0 and the resistor connected to the TIP120. The reason for this is that the GPIO-0 pin has to be at HIGH level when the ESP is powered up. If that is not the case the ESP switches to program mode which is obvious something we do not want. So you put the switch in the off position when you power up the ESP and after a short while put the switch in the ON position and you are ready to go.


Also DO NOT forget to cut the stripboard leads where it is needed. That is between the two resistors for the LM317, under the ESP8266-01 to separate the left side contacts from the right side and between the LM317 and TIP120 setup and the part that seperates the ESP8266-01 from the rest. Just examine the stripboard and schematics well and you know where to look.





My power supply is as stated before a 5Volt USB power supply. I bought it at the dollar-dollar shop (called Action in the netherlands) and it delivers 2.1 Amps.




The last step was to adapt the software for the use of just one IO pin and I changed the text to something more suitable for the project.

Now the only thing that needs to be done is to make a proper housing. But that is easy if you own a 3D printer like me.

And to give credit to where credit is due: all schematics, breadboard and stripboard drawings were made with Fritzing.

I have more projects with the ESP8266 coming up like a rain detection system that twitters when it is raining. In the end I want to build a complete domotics system, so watch this space.

ESP Ledsptrip controller source code

Disclaimer: check, double check and triple check your stripboard before you attach it to the power. Test each part, LM317 setup, TIP120 setup, ESP8266-01 setup individually before you connect it all together. I take no responsability for blown fuses, burnt down houses or whatever. Be sensible, check my schematics, breadboard layouts and stripboard layouts before you use them and do so on your own risk.



Till next time
Have fun

Luc Volders