Thursday, December 1, 2016

Check Check and Doublecheck !!!

One of my projects was nicely coming along. In reality it was just a stupid project being a portable thermometer using an ESP8266 that displays the temperature on a web-page. So nothing special. The breadboard version worked like a charm to I transferred it to some stripboard. And then disaster struck.

It just did not work. The dreaded blue smoke materialised and my ESP was fried !!! Damn what happened ???

So I checked my stripboard soldering over and over and I just couldn't find a fault. There was only one thing left to do: check the power supply.


 
My intention was getting power from a USB power source be it from a computer or a power bank.
For that reason I use cheap USB power cables from the dollar store. I cut the cable and strip the wires.




The wires are colored just like they need to be: Black for ground, Red for VCC Green and White for the USB data channels.




I hooked up a mulimeter and it looked allright. 4.9 volts is great. But hey look at that closely. It does not say 4.9 volt !!! It says - 4.9 volt.



So I took out my trusted polarity checker (find the sory on that by CLICKING HERE) and hooked it up. Black to Black and Red to Red. And then it was obvious. The red light was on. Polarity was reversed !!!!


And then I switched the power leads: Red on Black and Black on Red and there it was: the blue led went on: everyting. ok.

So there you have it: the color of the power leads from the USB cable were reversed. The GND was on the RED cable and the VCC on the black cable !!!! Some idiot in the factory switched the colors of the cable. Everything on the connector side was ok, just the colors of the cable had been switched.

So before you hook anything up:, NEVER TAKE ANYTHING FOR GRANTED and CHECK !!!! Check !!!! CHECK and DOUBLECHECK !!!

This is the first time I say in my web-log: this was no fun at all.

Till next time.

Luc Volders

P.S. Check and Doublecheck !!!

Sunday, November 13, 2016

Bubble level

At my job collegues use this bubble leveler. They had some spares and dropped them on my desk. They know I am a tinkerer and am always interested in all kinds of technical stuf.




This leveler is however small and I immediately had (as always) some wild (weird) ideas. For realising them I needed a larger leveler. So I started thinking on how I could make one myself. The general idea behind it is after all dead simple.






So my first stop (and only one) was at a DIY depot. There I found some clear plastic foodsafe tube. The outer diameter was 10mm and the inner diameter 8mm. So it was a thick tube with thin walls and therefore just what I needed.




I cut about 9 cm of the tube. Then I closed one side of the tube with my glue gun. Then I waited till the glue cooled down.


Next step was to fill the tube with water. I did not fill it totally as I obviously wanted a bubble. Then I  closed the other side with my glue gun.



And presto. It was done.

However the tube was not straight. As you can see it was bended. Now that is not really usefull for a bubble leveler.


To the rescue comes my faithfull Beagle 3D printer. So I printed a frame for it. Now it functioned it just like I wanted it to do.

So it works. But now what.

Well I have some ideas for projects for this. But to make it really usefull the contrast between the bubble and the water is not big enough. So I started experimenting with ink in stead of water. Well that was no success as the ink dried and I ended up with a tube with solid black walls.



So then I used syrup. A real dark syrup and that worked like a charm.

Just make sure that you test in a long term that the fluid you are using will not dry out and you'll have a cheap bubble-level.

Any of you have a clue on what I am going to make with this..........Hint: movement detection.

Till next time.
And have fun.

Luc



Tuesday, November 1, 2016

ESP8266 getting the right time with the LUA language

Sometimes you need the right time in your projects. For example when you need to registrate a sensor reading at the right time or date. Or you want to make a clock etc. etc. etc.

The easiest way is to put the time in your source code and then start your program. But that is not veryy efficient. Firstly you will get a delay by uploading the program to your ESP, second the build-in hardware times re surely going to deviate from the real time, and last but not least if there is a short power failure the program will start again with the time setting that is pre-programmed.

So I found a LUA program that gets the time on a weblog maintained by Peter Jennings. You can find the weblog here:

http://benlo.com/esp8266/esp8266Projects.html#googleTime

Now lets examine the code.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
-- retrieve the current time from Google
-- tested on NodeMCU 0.9.5 build 20150108

conn=net.createConnection(net.TCP, 0) 

conn:on("connection",function(conn, payload)
            conn:send("HEAD / HTTP/1.1\r\n".. 
                      "Host: google.com\r\n"..
                      "Accept: */*\r\n"..
                      "User-Agent: Mozilla/4.0 (compatible; esp8266 Lua;)"..
                      "\r\n\r\n") 
            end)
            
conn:on("receive", function(conn, payload)
    print('\nRetrieved in '..((tmr.now()-t)/1000)..' milliseconds.')
    print('Google says it is '..string.sub(payload,string.find(payload,"Date: ")
           +6,string.find(payload,"Date: ")+50000))
    conn:close()
    end) 
t = tmr.now()    
conn:connect(80,'google.com') 


Well the code is actually quite simple. It opens a web-connection to google.com then retrieves the information starting with Date: and there we have the time.

So when I loaded the program into my ESP I got the following result:



Anything wrong with that ??
Well yes. Actually I am living in the Netherlands. The program prints GMT time which is 1 hour off. Next there is no difference in summer- and winter- time so that puts the time another hour off. So for me the time is 2 hours off.

Now I could make an adjustment in the software for that but this would make things complicated. So I went looking for anonther solution.

This particular line:

    print('Google says it is '..string.sub(payload,string.find(payload,"Date: ")
           +6,string.find(payload,"Date: ")+35))


actually looks in the retrieved information for the word Date: and prints everything from Date: to the next 35 characters.
So lets expand this and see if we can find any thing interesting in then rest of the retrieved information. So I altered the code in:

    print('Google says it is '..string.sub(payload,string.find(payload,"Date: ")
           +6,string.find(payload,"Date: ")+5000))


And nothing happened. No extra information came up.

So I needed a different source.



I looked at the website time.is this site actually puts the right info on your screen. As the info on the site itself displays: Time.is displays exact, official atomic clock time for any time zone.

So let's see if we can adapt the code from Peter Jennings to our needs.





And there it is, right after the word Expires: the real time at my location.

So the adapted code is:


 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
-- retrieve the current time from Google

wifi.setmode(wifi.STATION)
wifi.sta.config("XXXXXXXXXXXXX","YYYYYYYYYYYYY")

print("Time Function")
conn=net.createConnection(net.TCP, 0) 

conn:on("connection",function(conn, payload)
 conn:send("HEAD / HTTP/1.1\r\n".. 
 "Host: time.is\r\n"..
 "Accept: */*\r\n"..
 "User-Agent: Mozilla/4.0 (compatible; esp8266 Lua;)"..
 "\r\n\r\n") 
 end)
 
conn:on("receive", function(conn, payload)
 print('Time.is says it is '..string.sub(payload,string.find(payload,"Date: ")
 +6,string.find(payload,"Date: ")+500))
 time = string.sub(payload,string.find(payload,"Expires: ")
 +9,string.find(payload,"Expires: ")+34)
 print("It is now ")
 print(time)
 print (" ")
a = string.sub(time,18,19)
b = string.sub(time,21,22)
print (a .. " hour")
print (b .. " minutes")

print(" ")
print(" ")
print("it is ".. a .. " hour " .. b .. " minutes")

 conn:close()
 end) 
t = tmr.now() 
conn:connect(80,'time.is') 

As you can see I made some small modifcations for your (and mine) convenience. The time is put in the variable called time (duh). I added 2 variables named a and b. They contain the hour and the minutes. This makes it easy to adapt to your own program needs. Next I printed the variables and printed a line in which they are used to display the right time.

Any flaws ???

Yes. Off course there is a pitfall.
The code gets the time from the internet by looking at your IP adress and getting info about this adress from your provider.  However it is possible that your provider is located in a different time-zone. Then you actually will get the time from the time-zone where the main acces-point of your provider is.
Here in the Netherlands that will not be a big problem as we are all in the same time-zone. However if you are living in the States or any other country that is divided in multiple time-zones you might run into a problem. That's worth checking before you use the modified code.

Till next time.
Have fun !!

Luc Volders

Saturday, October 1, 2016

Nuw: the resistor color code clock

I wanted to make a clock. Clocks can be cool. However the internet is filled with projects about making clocks, so I wanted to make something special. And that is how Nuw originated.

Nuw is an abbrevation of Nerds Ultimate Watch. It is ofcourse presumptuous to use such a name but hey I invented it so I can name it whatever I want.

I had this stupid idea about making a clock that displays the time not as usual in figures but in resistor colour codes. Let me explain.

Every maker/tinkerer knows about resistor codes. Resistors don't have figures printed on them that tell the value. No their value is expressed in colour codes. And these codes are an international standard. So let's look at the colours that represent the figures.




The real resistor colour chart is a bit more complicated as I needed. I just need the colors with the accompanying figures.

Now let us look at time.




We display the time as 2 figures for the hours, 2 figures for the minutes and 2 figures for the seconds.

Well that can easily be interpreted.
Looking at the table 12.30 would translate into Brown, Red, Orange and Black.

Lets take another example. 15.47 would translate in Brown, Green, Yellow and Purple.

Sounds easy.

To display hours, minutes and seconds I would need 6 RGB leds. As each led needs 3 pins for the colour this would add up to 18 pins on a processor. That would rule out an Arduino. I would need an Atmega2560 for controlling all these pins. And that would be a total overkill. So lets skip the seconds and keep it to the hours and minutes.

To achieve this I would need 4 RGB leds. As each led has 3 pins for choosing colour I would need 12 pins on a processor. I would also need at least 2 pins for attaching switches for setting the time. One switch for setting the minutes and another one for setting the hours. So that sums up to at least 14 pins. This means I should be using an Arduino. And I did not want to use an entire Arduino for just a clock. So I could take an Atmega 328, program it with an Arduino board and put it in a dedicated pcb. That should work but I did not like the idea.

I decided to take a different approach.

If I was to use Neopixels (WS2812 led's)  I just needed 1 datapin. Using two buttons for setting the time would add 2 datapins. That sums up to 3 pins on a processor. So I could use an Attiny85 !!! Now we're getting somewhere.

I herebye give you the schematics and the breadboard layout made with Fritzing
For clarity of the schematics I let the power lines to the neopixels out. They speak for themselves.





So I build a prototype on a breadboard and started coding.

Coding was actually easier as I expected.



I used the Adafruit Neopixel library and the Time library.

The code starts with initialising the libraries and then declares an array in which the colors that correspond with the figures are declared.

The function setresval() sets the resistor color code to the neopixels.
The first Neopixel should display the values 0,1 or 2
The second neopixel should display the values 0 to 9. These take care of the hours.
The third Neopixel should display the values 0,1,2,3,4 and 5
And the last neopixel should again display all the values from 0 to 9. These take care of the minutes.

The Time.h library takes care of the hard work. It automatically puts the hours forward if the minutes reach 59 and resets the clock to 00:00 if 24 hours have past.

At the bottom in the code is a function called keyhourl().
This code watches if a button (toets1 or toets2) is pressed. If that is the case it looks which button was pressed and accordingly add's 1 to the hours or 1 to the minutes. This ables us to set the time.
The neat part is that if you keep the button pressed the code will cycle through all values, so you do not have to push the button like a madman to get at for example 55 minutes.

The code works flawlessly.

The casing.

I first put the prototype on stripboard. That gave me an idea about how big the pcb would be. I soldered the switches on a separate pcb so I could arrange to have them at the side of my casing.

I would have loved to make a wristwatch however I do not own (or can buy easily) those nice Lipo batteries. So I had to use AAA batteries.

As the Attiny is not voltage critical, and neither are the Neopixels, I could use 3 AAA batteries giving me 4.5 volts which is sufficient.



Using Tinkercad I designed my casing.
You can find the design here:  https://www.tinkercad.com/things/6RO5IBVzPAn-nuwcase01
And the design for the lid here:  https://www.tinkercad.com/things/gOw2PweYORx-lid-for-nuwcase01

As at the time I was using my old Prusa I2 which is not as accurate as my new Beagle I designed the case without holes for the neopixels and switches. So I made the case solid and used a drill to make the holes.

The pictures below shows you how it is all put together.









It really works.

After getting used to it, it actually is quite easy to set the time.





I took the clock several times to my work and already have some collegues who yell at me: "Hey Luc it is already brown-green o'clock, time for a coffee break !!!"

The 3 AAA batteries supply enough current to let the clock work for about 8 hour.

A small flaw.

Well not exactly a flaw but a shortcoming. It is a bit difficult to distinguish brown, red and orange. This is due to the way colours are mixed in RGB-leds. If anyone has a better colour code for brown, red and orange please mail me the details.

Room for improvement ???

Yes there always is.

Small batteries so I could turn it into a real wristwatch would be nice.

Or I could attach a power supply to it. Should be easy. Any 5 volt supply (like a phone charger) could do the job.

Another Idea is to attach a RTC (Real Time Clock) so it would no longer be necessary to set the time.

When using a power-supply a blue-tooth connection with an Android Phone could easily be made for mail and sms alerts etc. It could even automatically set the time.

Replacing the Attiny with an ESP8266 is not a very big problem. However that would certainly need a power supply in stead of batteries. But then the ESP could fetch the right time automatically.

Oh and then this:

When you build this project and have it on your desk and people start complaining that it is to difficult to read the clock just tell them that this clock lets them contemplate on the concept of time.

This was a really fun project to figure out, design and build.

Now as usual the only thing that rests me is to give you the source code and the STL files so you can print one for yourself. You can find these on Github with the following link:


https://github.com/Lucvolders/NUW

Till next time.
Have fun

Luc Volders

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