Friday, January 19, 2018

Wifi Relay

I have shown you how to control leds and relays over wifi before on this blog. The first time was in May 2016 when I showed you how to control a ledstrip with an ESP8266. You can re-read that story by clicking here.

The second story was about a relay-server that could be accessed over the internet but as a bonus also has manual control. Something I have not seen before and still have not seen in other stories (however the internet is a big place so I can be mistaking). You can re-read that story by clicking here.

These projects and most projects you can find on the internet have one thing in common and that is that they all work using a web-page to send commands to the ledstrips, relays etc.

There might be moments that you want to control things over wifi but not use a webpage for this. An example would be that you need the project being accessed from the internet or your local network, but not seen by everybody or controlled by everybody. I can imagine that you do not want your kids/visitors to control the lights or electronics in your mancave.

Therefore we are going to control an ESP8266 in a totally different way. We are going to make our own Android APP in Mit's App Inventor and write a special program for the ESP8266 that listens to the APP. There is no web-page, so the ESP8266 can only be controlled from the APP and even better: only if you know the exact commands to control it.
To be specific: the app will have buttons to put leds on and off and give an audible feedback in the form of spoken words like I demonstrated in the project that can be found by clicking on this link: http://lucstechblog.blogspot.nl/2017/10/phone-speak-to-me.html

Don't worry. Writing your own APP with App Inventor is very easy and what is more you will get all source code and even the Android APK file here so you can use it right away or alter things to your own needs.

Let's make the APP

This is not going to be a tutorial on how to use App Inventor. I urge you to play around with this program and definitely have a look at all the provided examples and tutorials. Also have a look at all the resources that can be found on the internet about App Inventor. But basically the program is so easy to use that you will be devellopping your own App's in no-time.

The Designer screen

Start with downloading the Wifirelay.aia source code to your computer. Then point your browser to http://appinventor.mit.edu/explore/
On the right side of the screen click on the orange square that says "Create Apps"
Now you can log in with your Google credentials. If you do not have a Google account make sure you get one first.
In the projects menu on the top of your screen choose -- import project(.aia) from my computer.



When done your screen will look the same as above.

On the right side of the screen you will find a column with all the components that are used in your App. Clicking a component will highlight it on the example screen and in the last column on the right side of the screen you will be able to alter the settings for that component.

As you can see there are a few labels that do nothing more as putting text on your screen. Then there is a textbox that allows you when running the App to fill in the IP adress of the ESP8266 that is going to be connected.
Next there is a tablearrangement which makes it possible to put components in rows and columns on the screen.
The tablearrangement contains labels with the name of the led and buttons for setting each led on or off.
The last two components are the Web1 and TextToSpeech1 component. They are very important and working in the back-ground. The Web component takes care of the communiaction between the ESP8266 and the App. The TextToSpeech1 component is going to be used to have the App speak out loud which function it has completed.



There is one thing I really want to Emphasize.
Look at the TextToSpeech1 component carefully. If you leave it at its default values the App will speak out any text in the language you have set as your default language in your phone. If that is English all is well. However my phone is set default to Dutch and therfore the text that will be spoken will sound very awkward. So if English is not the default language on your phone you can change the setting for the TextToSpeech1 component to English or alter the text in the program so it will speak your language.

When all is set switch on the right (top) side of the screen to the blocks section where the actual program will be written.

The Blocks




As you can see the program is divided in 6 blocks. Each block starts a function when one of the buttons on the screen of the phone is pressed. There are six buttons (Led 1 ON, Led 1 OFF, Led 2 ON, Led 2 OFF, ALL ON and ALL OFF) and as you can see each button has its own block of code.





Let's look at one of the blocks in detail.

This is the part of the program that will set Led 1 ON.
This block is executed when the button Led1_on is clicked.
If the button is clicked a web-url will be generated that consist of the IP adres which is found in the text-block IP_adress followed by "/sw1on".
With this information the Web1 function is called and when finished the message "Lamp 1 on" will be heard on your phone as an audible check.

That's all.
All blocks are similar exept for the command that is send through the web and the audible feedback.
Make sure that you alter the words that will be spoken in your own language or set the TextToSpeech1 component to English like discussed above. You can alter the "/sw1on" etc commands in the program, but then make sure that you also alter them in the C program for the ESP8266 that follows in the next steps.



The picture above shows you how the actual screen will look on your Android phone or tablet.

Expanding the APP

As you will have guessed by now it is very easy to expand this App for many more leds/relays. Use the designer screen to add more buttons and then switch back to the blocks screen. First click on a block and then choose Duplicate Block by clicking the right mouse button. Alter the name in the - when - section to the name of the new button. Do not forget that you will have to duplicate both the ON and OFF block and make sure you alter the "/sw1on" and "/sw1off" in the number you are going to add and alter also the speech component.

If you have altered the blocks then let Mit's App Inventor build a new APK for you. If you have not altered anything you can install the provided APK at the bottom of this entry.

The ESP8266 program.

Now the App is ready we'll have a look at the ESP side of this project.

This is written in C++ (generally called Arduino code) and edited and uploaded with the Arduino IDE. So I presume that you have installed the ESP8266 prerequisites in the Arduino IDE. If not do so now. The internet is full of tutorials for this so that should be no problem.

Let's have a look at the program.


 /* 

=================================================  
 *  Controlling NodeMCU through an Android APP  
 *  
 * Devices  
 *  ==> Relay1 represented by led 1  
 *  ==> Relay2 represented by led 2  
 *    
 * Groups   
 *  ==> All Devices ON/OFF  
 *  
 * Program by Luc Volders  
 * http://lucstechblog.blogspot.nl/  
 *=================================================*/  
 #include <ESP8266WiFi.h>  
 WiFiClient client;  
 WiFiServer server(80);  
 const char* ssid = "XXXXXXXXXX";  
 const char* password = "YYYYYYYYYY";  
 String command =""; // Command received from Android device  
 // Set led/relay Pins  
 int switch1 = 13;  
 int switch2 = 15;  
 void setup()  
 {  
  Serial.begin(115200);  
  pinMode(switch1, OUTPUT);   
  pinMode(switch2, OUTPUT);    
  digitalWrite(switch1,LOW);  
  digitalWrite(switch2,LOW);  
  connectWiFi();  
  server.begin();  
 }  
 void loop()  
 {  
   client = server.available();  
   if (!client) return;   
   command = checkClient ();  
      if (command == "sw1on") digitalWrite(switch1,HIGH);  
   else if (command == "sw1off") digitalWrite(switch1,LOW);  
   else if (command == "sw2on") digitalWrite(switch2,HIGH);     
   else if (command == "sw2off") digitalWrite(switch2,LOW);  
   else if (command == "allon")   
   {  
    digitalWrite(switch1,HIGH);  
    digitalWrite(switch2,HIGH);  
   }  
   else if (command == "alloff")   
   {  
    digitalWrite(switch1,LOW);  
    digitalWrite(switch2,LOW);  
   }  
   sendBackEcho(command); // send command echo back to android device  
   command = "";  
 }  
 /* connecting WiFi */  
 void connectWiFi()  
 {  
  Serial.println("Connecting to WIFI");  
  WiFi.begin(ssid, password);  
  while ((!(WiFi.status() == WL_CONNECTED)))  
  {  
   delay(300);  
   Serial.print("..");  
  }  
  Serial.println("");  
  Serial.println("WiFi connection established");  
  Serial.println("IP number is : ");  
  Serial.print((WiFi.localIP()));  
 }  
 /* check command received from Android Device */  
 String checkClient (void)  
 {  
  while(!client.available()) delay(1);   
  String request = client.readStringUntil('\r');  
  request.remove(0, 5);  
  request.remove(request.length()-9,9);  
  return request;  
 }  
 /* send command echo back to android device */  
 void sendBackEcho(String echo)  
 {  
  client.println("HTTP/1.1 200 OK");  
  client.println("Content-Type: text/html");  
  client.println("");  
  client.println("<!DOCTYPE HTML>");  
  client.println("<html>");  
  client.println(echo);  
  client.println("</html>");  
  client.stop();  
  delay(1);  
 }  

First replace the XXXXXX and YYYYY in the program with the name and password for your router.

As you can see I use pin 13 and 15 as the pins where the leds will be attached (which equals D7 and D8 on the NodeMCU). You can alter them for your own needs or leave them as they are. If you added more switches in the App you need to assign more pins for leds.

Halfway down the program you cann see the checks for the commands sw1on and sw1off etc.
If you have altered the names for the commands in your App you will need to alter them here to. And if you have added more buttons in the App you will need to add more commands here.

The program has some serial communication which can be helpfull when debugging it. If all works flawlessly you can comment the serial communication out or delete the relevant lines.

The rest of the program takes care of receiving the commands from the App.

Upload the program to your ESP8266 and you're set to go.

The Hardware



The hardware setup is straightforward as the above breadboard setup shows you. I have used a red led and a blue led for demonstration purposes.The delimiting resistor is 220 ohm, and attached to GPIO13 and GPIO15.






The schematics are pretty straightforward too and the photo shows you my setup on a breadboard.

You can change the leds for dedicated relays like I used in the relay commander project that you can find by clicking here.

Or use a general relay controlled by a BC547 as in the project you can find by clicking here.


Where is it

In the App you need to fill in the IP adress of the ESP8266. There are 2 ways to find that IP adress.

You can use the Arduino IDE and open the serial monitor at 115200 baud. The program will show you the IP adress.

The second way is to open the web-page of your router like I did in the following picture.


The four icons on the bottom of the screen are my wired stations: a raspberry network server attached to my Epson printer, My Computer called Nescio, my Domoticz home automation system and a Buffalo Nas.
The three top Icons represent my wireless stations. The first one is an ESP that is a permanent Thermometer that serves a web-page and send info to Thingspeak (all written in ESP-Basic), my Andoid Phone and an unknown station. That last one is the interesting one.


These are the details for the unknown wireless device and there we have the IP number we are looking for.

Real life demo

Fill in the found IP-number in the App and start pushing the buttons.

 

The video shows you how the app functions although that is very obvious. You can clearly hear how the speech component works.

Remember the great dictator series on this blog ???
Well then you will know what the next step will be. Commanding your lights with your voice.

Rests me only to give you the links to the source code and the APK file for direct install:

https://github.com/Lucvolders/Wifi-relay

Till then.
Have fun


Luc Volders

Friday, January 12, 2018

All stories organised

As this blog grows it becomes more and more difficult to find stories that might interest you.

So I made an index.
You can find it on the top-right side of this page right below the banner under the chapter pages. you can also click (or save) this link:

http://lucstechblog.blogspot.nl/p/index-of-my-stories.html

The index is divided in chapters that represent the point of intrest.
Under each chapter you will find the related stories and a short description.

Look at the sample below:

IOT (Internet of Things)

Back to Basic - introduction to ESP-Basic
Burglars invited - Be carefull what you publisch on public sites
Cheapskate - test wether your fridge light is on or off
ESP Controlled ledstrip - Control a single color ledstrip from a webpage
Google Home and the ESP8266 - Turn on your devices with your voice
IFTTT part 3 Alert over IFTTT - Tweet an alarm when your PIR has noticed motion
IFTTT part 4 - Send a notification to my phone
Rain Sensor - Get an alert on a webpage when it rains
Relay Server  - Control your lights over the internet AND manual


As you can see the point of intrest in this part is IOT and there are at the moment of this writing 9 stories related to IOT alphabetically arranged.

From now the index will be updated each time a new story is published and I will put a pointer to the index on each new story that is published.

Hope you find this usefull.

Luc

Friday, December 8, 2017

Lightmouse

While surfing over the internet I stumbled upon the Leap Motion Controller and I was flabbergasted. It was something that that really amazed me. Controlling your computer with your hands instead of a mouse. I wanted one.

Then I started thinking. Wouldn't it be possible to make something like this by myself. Well not actually tracking the movement of your fingers. That would be to complicated. But tracking the movement of a hand should be possible.

The general idea was that when your hand moves over a surface the place where the hand is, is in the shade and the rest would be in the light. And that is something you can easily measure by using LDR's (Light Dependend Resistors). So I made a simple setup.



I used two small breadboards next to eachother. This makes it possible to put the LDR's on the breadboard at a certain distance. I attached the LDR's to the analog ports of the Arduino Pro Micro.

Mind you: for this project you really need an Arduino Pro Micro as this has a real USB interface and not a USB-serial interface. We will be needing the USB interface for simulating a mouse.

The LDR's have a pull down resistor for more accurate measuring. To calculate which value the pull-down resistor needs in your particular case use the formula described in this article.
If you do not use the right pull-down resistors the setup will not function  as intended and react poorly at your movements.
In my setup I am using 10K resistors because my setup is intended to work in full light. However if you are using this in more ambient circumstances make sure you alter the values of the resistors using the described formula in the formentioned article.

The first tests were done by just reading the values the LDR's would give when I moved my hand above it. And the results were very satisfying.

Now I had to find the right formula for making something usefull out of this.

Let us look at the following simplified setup.





The square represents the total setup and the black dots represent the LDR's.

If I want to go left my hand has to cover LDR A and C.
For going right it has to cover B and D
Up means covering A and B
Going down can be achieved by covering C and D

By covering the individual leds I indicate that I want to go diagonal.

This can be easily represented in a formula.
Think about this.
If I cover LDR A and C they will get less light as LDR B and D.

X direction =  (A+C) - (B +D)

If the outcome is negative I am moving left. If the outcome is positive I am moving right. Remember that the LDR's give a higher value where there is more light.

Y direction = (A+B) - (C+D)

Same drill as the X direction.

The individual leds are even easier.

If the Value of LDR A drops then I am covering the LDR and want to move UP-LEFT.

And this is really all that is to it.

The only thing I need to test is wether I am actually moving my hand above the setup.
That can easily be done by the following test:

  x = ((A+C) -(B+D));
  y = ((A+B )- (C+D));
  axy = (abs(abs(x)-abs(y)));
 
  if ((abs(x)>25) && (abs(y)>25))

Look at this formula. It just tests if the difference between X and Y is bigger as 25 and that indicates that something is going on above the LDR's. I have substituted the formula in my program by using the variables s1 to s3 which represent the analog lines A0 to A3.

Now we only have to tell the Arduino Pro Micro that it has to act as a mouse by the following command:

void setup()
{
  Mouse.begin();
}

And here we get at a more difficult part of the program. Look at the following lines:

  if ((x<0) && ((abs(x))>(abs(y))) && (y>0) && (axy>100))
    {
      //going left
      Mouse.move(-10, 0, 0);
    }


Let's examine it in detail.

 if ((x<0) && ((abs(x))>(abs(y))) && (y>0)

The first part just tests if  X = smaller as 0. If that is true then this means you want to move left.
As a safety measure I also test if the X value is really bigger as the Y value. That indicates that there is indeed less light on the X LDR's.

&& (axy>100))

This last part tests wether there is a significant difference between the X and Y values. That is to make sure it is my hand moving above the LDR's and not just some shade of a cloud passing by.

Just one last thing to do:

Mouse.move(-10, 0, 0);

And that is why you need to use the Arduino Pro Micro.
This command actually moves the mousepointer of your PC (or Raspberry) to the left by 10 pixels. The 0 following the -10 makes sure that the mouse stays on the same line (Y-coordinate( and just the X moves. The second 0 indicates that the scroll wheel of the mouse should do nothing.

So here is the full listing:



/*Light Mouse
  Luc Volders

Decides on which way the mouse will go by checking
which LDR's get light on and which do not

using 4 LDR's put in a square form
top:    A1, A3
bottom: A0, A2
*/


int s1, s2, s3, s4, x ,y, axy;


void setup()
{
  Mouse.begin();
}

void loop() {
  
  s1 = analogRead(A0);
  s2 = analogRead(A1);
  s3 = analogRead(A2);
  s4 = analogRead(A3);

  x=((s3+s4) -(s1+s2));
  y=((s1+s3)-(s4+s2));
  axy = (abs(abs(x)-abs(y)));
  
  if ((abs(x)>25) && (abs(y)>25)) // test for action
  {
  if ((x<0) && ((abs(x))>(abs(y))) && (y>0) && (axy>100))
    {
      //going left
      Mouse.move(-10, 0, 0);
    }
  if (((x>0) && (y>0)) && (axy>100))
    {
      //going right
      Mouse.move(10, 0, 0);
    }
  if (x<0 && y<0 && axy>100)
    {
      //going up
      Mouse.move(0, -10, 0);
    }
  if (x<0 && (abs(x)<abs(y))&& y>0 && axy>100)
    {  
      //going down
       Mouse.move(0, 10, 0);
    }
  // -------------------------------------------------------
  // schuin
  // -------------------------------------------------------
    if (((x<0) && (y<0)) && (axy<100))
    {
     // moving left-up
      Mouse.move(-10, -10, 0);
    }
    if (((x>0) && (y<0)) && (axy<100))
    {
      //moving right-up
      Mouse.move(10, -10, 0);
    }
    if (((x<0) && (y>0)) && (axy<100))
    {
      //moving left-down
      Mouse.move(-10, 10, 0);
    }
    if (((x>0) && (y>0)) && (axy<100))
    {
      //moving right-down
      Mouse.move(10, 10, 0);
    }
  }
  
  delay(50);
}


After I was sure everything worked fine on the breadboard setup I made an experimental setup using a cardboard.


And after thorough testing I sat behind my computer and designed a casing. This was done in Tinkercad. This design proves that Tinkercad is quite capable.








And this is how it looks in real life.



And man does it work !!!!



I am sorry the video is of such a bad quality but it is the best I could do in my crammed man/cave. I had to make the video using one hand and using the other hand to operate the device.

It also works on my Raspberry Pi and using a USB/OTG adapter it also works on an Android device. I tried it on my Phone and on a tablet with great results.

A lot of possibilities come to my mind for this device. Using it as a joystick for games is obvious. How about adapting the hardware and making a remote for a model boat or car. Gesture controlling a Power-point presentation is another option. Use your imagination.

You can as always find all files on my Github repositry.
https://github.com/Lucvolders/Light-Mouse

So try this for yourselves and have fun.
Till next time

Luc Volders

Friday, December 1, 2017

Analog Pull-Down resistor

We all realise the importance of the pull-up resistor on a digital input pin.
Without a pull-up resistor the initial state of a digital pin is floating and we never will get an accurate reading.

However I never realised how important the pull-up resistor is in an analog circuit. And now I understand it fully I can give you an excellent simple example that demonstrates how valuable such a pull-up resistor is.

Normally an Arduino or an ESP-8266 can read it's analog input and gives it a value between 0 and 1023.
Lets see what happens when we do not use a pull-down resistor and attach an LDR directly to the analog input. In this example I am using an ESP-8266.


Look at the breadboard. The LDR is on one side connected to 3.3 Volts and the other side directly to the analog input of the NodeMCU.






timer 100,[test]

wprint |<h1 style="text-align:center;">Luc Volders</br>Light Tester</br>|
wprint "<br/>"
textbox value
wprint "<br/><br/>"
button "<h2>Off</h2>", [Off]
wprint "<br/>"
wait

[test]
sensor =  io(ai)

value = sensor
wait

[Off]
end


So I wrote a small BASIC program that just reads the analog input port and displays it on a web-page.




When fully exposed to the light the analog reading was 958. When fully covered the reading was 984. Well it kind of works however there is not a lot margin for error. So this is not very usable.

I started searching the net for an LDR setup and indeed there were many examples. They all used a 10K pull-down resistor.



I altered my breadboard setup and attached a 10K pull-down resistor. And indeed it worked.








The value I measured when the LDR was in full light was 527 and when covered with my finger I measured 933. Now this is a much wider range so there is a wider range measurable when the LDR is just partly covered. However it was still not using the full range.


AXEL BENZ FORMULA




Then I found the  Axel-Benz formula.
The Axel-Benz formula is honorably named after one of the first teachers of Physical Computing at the FH Postdam.

How does this formula actually works out.

The formula R-ref = SQR (R-min * R-max) tells us that the value of the of the pull-down resistor should be the Square Root of the (minimal resistance * maximum resistance).

Lets start with measuring the minimal and maximum resistance. We'll do that using our trusted multimeter.





As you can see the value I measured when the LDR was exposed to full light was 420 Ohm. When I covered the LDR with my finger I measured a value of 18.500 Ohm. Now I would have expected a much higher resistance when the LDR was covered so there might be some light leaking around my finger.

Now let us use these figures in the formula.
The formula is: R-REF = SQR (MINIMAL * MAXIMAL)

Lets substitute our figures into the formula:
R-REF = SQR (420 * 18500)
R-REF = SQR (7770000)
R-REF = 2787

This gives us a resistor vaule of 2787 OHM. The nearest by existing value that we can use is a resistor of 2.7K


Therefore I substituted the 10K resistor on the breadboard to a 2.7K version.








And the result is fantastic. The measured values now vary between 257 and 847. This a much broader range in which we can measure more accurately the amount of light that is exposed onto the LDR.

Arduino test


int sensorPin = A0;   
int sensorValue = 0;

void setup() 
{
  Serial.begin(9600);
}

void loop() 
{
  sensorValue = analogRead(sensorPin);
  delay(sensorValue);
  Serial.println(sensorValue);
}

The above experiment is done with an ESP-8266. But how would it work on an Arduino. Well here is the code I used for measuring the Analog port.


I measured the value on port A0.



And here you can see that the values I achieved are almost the same as the ESP gave.

Is everybody Stark Raving Mad then ???

Why on earth is everyone using a 10K resistor then. Has the world gone mad. Well actually yes it has. Just look around you. however not concerning this  particular case.

When you have a full bright light the LDR will have a value of about 0 to 10 OHM. In absolute adrkness it will be around 10000000 (10 meg). Now if we use these values in the formula it will work out as follows:

R-REF = SQR (10 * 10000000)
R-REF = SQR (100000000)
R-REF = 10000

And there we have the 10K value.

However as we saw in the beginning of this story this value did not work out well in this particular case.

So the lesson learned is to always calculate the best value for the project you have at hand.

Till next time
Have fun

Luc Volders

Friday, November 24, 2017

Thingspeak

This weblog has described many projects that connect all kinds of sensors and switches to your network. We had an ESP Controlled ledstrip, a rain sensor, an ESP controlled relay, a thermometer and many more.

All these projects have something in common and that is that they attach an ESP to a web-page which can be controlled from your computer or phone. This works great when you are inside the environment of your wifi home network.

However not all projects are intended to be used from within your home or office. Sometimes you need to control things from another location (your office, on a holliday, visiting friends etc). That implies that you need to open a port on your home router so the information can get out your local environment. This is called port-forwarding.
So if you have multiple sensors and switches attached to multiple ESP's in your house you will need to open many ports on your router and that could (mind you I do not say "will") bring a safety issue. Opening ports on a router may open a port to a hacker, and that is something we certainly do not want to happen.

There are multiple solutions to this. One involves an intercommunication system amongst your ESP's. Meaning that all your ESP's talk to eachother and just you have one central system (being an ESP or a Raspberry) talking to the outside world. That is not the solution I am going to talk about here.

The solution I am going to discuss is using an external IOT platform.

What is an external IOT platform.

Basically it is a computer system run by a company that has an internet connection and allows you to send data to. This data will be put on an open or private webpage which you can access from any part in the world.
The advantage is that any device in your network only has to send data to this computer just like your home computer sends and receives data to and from the internet.

No need to open ports in your router, and often they offer a fancy interface that is easy to use. So there is not a lot of programming hassle.

Thingspeak




In this example I am going to demonstrate how you can put the information from the ESP-Thermometer on to the world-wide-web and read the temperature in your home from any place in the world. I am using the Thingspeak service for this as it has a very easy interface which can be used easily from ESP-Basic or the Arduino environment.

So the first thing you will have to do is to visit the Thingspeak website: https://thingspeak.com/

If you not have an account already (if you have you would not be reading this) Sign Up for an account. You will be asked an e-mail adress, a user ID (which you can define yourself) and a password. Remember both the user ID and the password. You wil be needing them both in the future.



After successfully signing up you will start at the channels page. At this moment you will not have any channels so choose to make a new one. You will be taken to a new page where you can fill in the details of this channel.



Above you can see that I filled in the first details for this channel. Give each channel an identifying name and fill in a fitting description. We will only have one field in this channel being the temperature. If you would have multiple sensors attached to your ESP you could for example have a second filed that represents a door movement. That way you could relate between an opening door and the temperature.


Scrolling down there are more fields which you can fill in which are not necessary exept one important one. That's the field you have to check to make your channel private or public.
Public channels can be accessed by anyone without even having to login. For now make it public.

Now press the Save button.





You will be represented with another screen that shows you the most important part: a chart with your workroom temperature. Off course there will be no information filled in yet.

As you can see there are 3 buttons. Two of them are important at first. The "More Information" button brings you to your own webpage. The "Data Export" button makes it possible to save all the data in a JSON, XML or CSV file on your computer for off-line analysing.



The most important TAB is the API Keys tab.
Here you will find your personal key for writing information to Thingspeak or reading information out of a channel.

For now we will only be looking to writing information to a channel. We will need the Write API key for that. So leave this screen open so you can easily copy the API key later on in your program.

Writing thermometer values to Thingspeak.


In the article "Oh no not another thermometer" I build a.....thermometer that displays the temperature on a webpage using an ESP and a Dallas 18b20 sensor. I programmed it in ESP-Basic and it has been functioning for many weeks in a row flawlessly. But it was only accessible from within my own home-network. Now we are going to bring it in the open.

Open a webpage and access the thermometer. If you do not know how to find it look at this article which gives you the basic information about ESP-Basic.


tel=0
Timer 5000, [start]

wprint "<!DOCTYPE html>" 
wprint "<html> <body>"
wprint |<body style="background-color:greenyellow;">|
wprint |<H1><span style="color: red;">|
wprint " A thermometer"
wprint "</H1>"
wprint "</span>"
wprint |<H2><span 

style="color: blue;">|
wprint "Temperature is now "
textbox test

a = "background-color:greenyellow;"
a = a & "display:block;width:80px;"
a = a & "border-style: hidden;"
a = a & "font-size: 22px;"
a = a & "font-weight: bold;"
a = a & "color: fuchsia ;"
cssid htmlid(), a
wprint "</span>"
wprint "</H2>"
Wait

[start]
test = temp(0)
test = ((int(test*10))/10)
tel=tel+1
if tel = 360 then
  tel = 0
  gosub [thing]
endif
wait

[thing]
sendthing = str(test)
SENDTS("MY-API-KEY", "1", sendthing)


return

Now open the Edit page and look how I altered the Basic Program.

What I wanted to do is to have the thermometer send it's information each half hour to the thingspeak channel. Therefore I altered three things in the program.

tel=0

I inserted this line to the top of the program to initiate a new variable.

[start]
test = temp(0)
test = ((int(test*10))/10)
tel=tel+1
if tel = 360 then
  tel = 0
  gosub [thing]
endif
wait

I altered this routine so that each time the routine is called (every 5 seconds which is set by the TIMER 5000 command) 1 is added to tell. And if tell has reached the value 360 (which is in time 5 seconds * 360 = 30 minutes) the routine [thing] is called.

[thing]
sendthing = str(test)
SENDTS("MY-API-KEY", "1", sendthing)
return

So eacht time (every 30 minutes) when this routine is called the string variable sendthing is filled with the actual temperature (test). And then SENDTS("MY-API-KEY", "1", sendthing) sends the information to field "1" in my Thingspeak channel. If you have more fields you obviously alter the "1" in the field you want to write to.


In the mean time the information on the local webpage will still be updated every 5 seconds.

You will have to substitute MY-API-KEY with your own key which you can find at the API-KEY tab in your channel. Make sure you use the "Write API Key" and not the read one which is used to read information from the page, nor for putting info on it.

That's all !!

Run the Basic program and just wait.




Here you can see the temperature in my room over a period of one and a half day.

More information needed

Thingspeak is free as in free beer as long as you do not exceed 8200 messages a day or 3.000.000 (yes 3 million) messages a year. You can update the info every 15 seconds.

If you have multiple sensors connected to an ESP you can add more fields in a channel or even open more channels depending on how you want to present the data. By opening multiple channels you have to use multiple API-Keys, one for each sensor.
If you are using multiple ESP's you can have them writing to the same channel, so you can have one graph with temperatures of several chambers in your house. Or you can open multiple channels, each ESP it's own.

Just decide what is most convenient for your projects.

However keep the limits in mind. And make sure the writing of data on each filed or channel overlaps as you can update only once every 15 seconds.

Minimalistic setup.

As ESP-Basic is really awesome for rapid devellopment I will give you a minimalistic setup here.

Timer 1800000, [start]
wait

[thing]
sendthing = str(temp(0))
SENDTS("MY-API-KEY", "1", sendthing)
return

These 7 lines is all it takes to send the information to my Thingspeak channel. The setback is that there is no fancy local webpage I can access on my phone or tablet to have a look at the temperature. You can only get the information through Thingspeak.

Even better.

To access your information you can log in from any place in the world to the thingspeak. But it even gets better. You even do not need to login for getting at your info.





Just go the Thingspeak website.

And in the top tabs choose "Channels" You will be presented by a similar page as shown here.



 
Now fill in your user ID on the right side of the screen and it will give you your channels




Clicking on the name of the channel in the blue banner will direct you to the information.




Remember this part of the setup page. You filled in "Make Public"
Setting a channel as public means that you even do not have to log in to access the information.

Be carefull

As said above a channell's information is accessible for anyone if it is set to public. That really means that anyone in the world can have access to the information. So be carefull.
Do not use your real name in Public information. Give no clues about who you are, what your location is etc etc etc.

Suppose you have a public channel that displays the information in your house. Or the water usage, or the time the lights are on etc etc etc. If the information is public this is valuable info for any burglar or thieves. Read here about this privacy issue: http://lucstechblog.blogspot.nl/2017/02/burglars-invited.html

In future stories I will show you how to send info to Thingspeak with the Arduino IDE and I will show you how to get information from the Thingspeak channel to perform actions on.


What more IOT platforms are avalable ?
 

Actually there are quite a few IOT platforms available. Some of them are equally easy to use like Thingspeak. Examples are Dweet and IotTweet which I am going to discuss in previous stories.

Others like Blynk and Cayenne IOT have many advantages and possibillities. However they require you to install libraries in your ESP. This will work while programming in the Arduino IDE but not (yet) in Basic. Programming is more difficult. And this article is aimed at fast results. Besides that Blynk is only free to a certain amount of channels.

Nevertheless it is something I will be checking into in future stories.

Till next time
Have fun

Luc Volders

Friday, November 17, 2017

Oh no, not another wifi thermometer.


I know. It is stupid. And at first I was not even sure why I was building it. As the internet is paved with ESP-Weatherstations and thermometers. And why on earth is the weather so interesting. Just look outside and you know what it is like. And then a reason came up. For testing all kind off IOT cloud services I needed a device that would constantly provided some data and what is easier as a thermometer to provide data.  However I had some demands.

Price.
It should be really low cost. and it is !!! I used an ESP-01 (1.57 euro) a Dallas 18b20 temperature sensor (0.98 euro) a LM317 voltage regulator (0.08 euro) , some resistors (about 0.05 euro) and a USB cable (about 1 euro). That sums up to 3,68 euro. Add some stripboard and wire and there is your complete thermometer for about 4 euro.
Naturally I printed the casing myself.

Simple.
This project should not take more as a few hours to build. I made a prototype on a breadboard and when that worked I transferred it to some stripboard. Programming was done in the unmatched easy ESP-Basic language.

Before we start.
Before we really start with this project I want to point out some basic knowledge articles I wrote that helps you understand how all fits together.
First read about the LM317T voltage regulator which allows you to provide your project with any voltage you might need. Read that story by clicking here.
 

And please read the introduction article to ESP-Basic which makes developping ESP8266 projects a piece of cake. The introduction article runs you through flashing ESP-Basic and using the web-based editor to writing your first programs.

Let's go.

Powering the project.

The ESP-01 works at a 3.3Volt power level. And the Dallas Temperature sensor fortunately also does so. I am going to power this project from a USB power source (be it a computer, mains adapter or powerbank). So the USB power, which is 5 volt has to be reduced to 3.3 volts.

As stated above I am doing this by the use of a LM317T voltage regulator. 5 Volt is supplied and reduced to 3.3 Volts.



As you can see from the schematics above we will need a resistor of 1.2K and a resistor of 2K to achieve this. Like  I said above: for more information about this read the article about the LM317T.



The breadboard shows you the setup.

The ESP side

For flashing ESP-Basic and programming I used my ESP-01 programming board which I described in detail in the story you will find by clicking here.



As you know the Dallas 18B20 needs a pull-up resistor of 4K7 to function. So I attached my programming board to a small breadboard on which I placed the resistor and connected the Dallas temperature sensor.

At first to make life easy I soldered some paperclip wire to the Dallas 18b20 wires so I could easily fit them on the breadboard. The paperclip trick is one I use often. For those of you not familiar with it click here to read the story. Later on I replaced them with dupont wires cut in half and soldered to the Dallas 18B20 wires.



 So when this all functioned I completed the setup on the breadboard.



And when all functioned as it should I put it on two left-over pieces off stripboard.

The program.

 Timer 5000, [start]  
   
 wprint "<!DOCTYPE html>"   
 wprint "<html> <body>"  
 wprint |<body style="background-color:greenyellow;">|  
 wprint |<H1><span style="color: red;">|  
 wprint " A thermometer"  
 wprint "</H1>"  
 wprint "</span>"  
 wprint |<H2><span style="color: blue;">|  
 wprint "Temperature is now "  
 textbox test  
   
 a = "background-color:greenyellow;"  
 a = a & "display:block;width:80px;"  
 a = a & "border-style: hidden;"  
 a = a & "font-size: 22px;"  
 a = a & "font-weight: bold;"  
 a = a & "color: fuchsia ;"  
 cssid htmlid(), a  
 wprint "</span>"  
 wprint "</H2>"  
 Wait  
   
 [start]  
 test = temp(0)  
 test = ((int(test*10))/10)  
 wait  


The program may look complicated but regard it closely and you will see that in reality it is not. There are some neat tricks in it though.

Let's simplify it first.

There are just 3 lines that actually are the real program core:

test = temp(0)
test = ((int(test*10))/10)


The first line reads the Dallas 18B20 temperature sensor. And the second line rounds it to 1 decimal.

textbox test

This line actually puts the temperature on the screen. Those are the three core lines. All that follows is just pimping it up.

Timer 5000, [start]

To make the program check the temperature each 5 minutes we use the Timer command as you can see in the line above.

wprint |<body style="background-color:greenyellow;">

This sets the background of the web-page in the color "greenyellow"

a = "background-color:greenyellow;"
a = a & "display:block;width:80px;"
a = a & "border-style: hidden;"
a = a & "font-size: 22px;"
a = a & "font-weight: bold;"
a = a & "color: fuchsia ;"
cssid htmlid(), a


That is an important block of CSS code.
What it actually does is to hide the contour of the textblock, give the textblock the same background as the webpage has and gives the text in the textblock a contrasting colour.
All this together hides the textblock from the screen and makes it look as if the text is printed direct on the webpage. And that is a really nice trick.


And here is the end-result.

Casing



The casing is identical to the casing I made for the PIR alarm (click here to look at that project).


 The difference is that the lid has no opening for the PIR. It is just massive


As you can see the case is far to large for such a small stripboard and therefore has one advantage: you can also power this project  with AA batteries.

That's it.

All that rests is to give you the links to the STL files so you can replicate or adapt this to your own needs.

https://github.com/Lucvolders/Wifi-Thermometer

Till next time, have fun

Luc Volders