ESP8266 + ds18b20 + thingspeak+ nodemcu
Update: 2016-02-06.
New greatly updated tutorial in new post with NodeMCU dev board and ArduinoIDE. A lot simpler approach.
Update: 2015-04-11.
Update with deep sleep now in new post. Testing the battery operation time in progress.
Update: 2015-03-18.
Updated the connection drawing with updated Fritzing part of ds18b20 with correct pin order also in the breadboard view. In the schematics the part was wired properly all the time. Note: don’t trust computers.
Simple temperature logger for your wifi surroundings is actually quite simple.
- ESP8266, wifi-enabled microcontroller board with gpio
- DS18B20, maxim 1-wire temperature sensor
- 4k7 ohm resistor, some wire
- 3v power source, for short term testing 2*1,5V AA batteries
Nodemcu firmware for ESP8266 is quite easy to work with. There is a module to interact with 1-wire temperature sensor readily available.
To set things up you also need a TTL converter, for example USB To RS232 TTL PL2303HX Auto Converter Module.
What you first need to do is connect ESP8266 to the ttl converter, 3.3v to VCC, GND to GND, RX to TX, TX to RX. And to enable the esp8266 you also need to connect CH_PD to VCC. After this you should be in a state where you can communicate with esp8266 using a serial console program and AT commands. After successful start the first thing is to get NodeMCU running on the ESP8266.
To flash new firmware to ESP8266 you need to boot the ESP8266 in upload mode and write new firmware, NodeMCU. Just connect GPIO0 to GND for upload mode and start flashing. More on flashing.
After flashing rebooting the ESP8266 without GPIO0 connecter should bring up some version strings to the serial console stating NodeMCU. This is good news as then all needed to do is to wire up the ds18b20 and upload init.lua and dallas.lua scripts. You also need to upload lua 1-wire -module (ds18b20.lua) to ESP8266.
Good tool to deal with ESP8266 and lua-scripts is ESPlorer. It lets you run scripts, upload files, run snippets and do bunch of other useful things with your ESP8266.
- ds18b20.lua
- init.lua
- dallas.lua
Before uploading init.lua set up your wireless network credentials.
init.lua
print(wifi.sta.getip()) wifi.setmode(wifi.STATION) wifi.sta.config("apname","password") print(wifi.sta.getip()) dofile('dallas.lua')
And before uploading dallas.lua set up your API-key for thingspeak.com.
dallas.lua
require('ds18b20') port = 80 -- ESP-01 GPIO Mapping gpio0 = 3 ds18b20.setup(gpio0) function sendData() t1=ds18b20.read() t1=ds18b20.read() print("Temp:"..t1.." C\n") -- conection to thingspeak.com print("Sending data to thingspeak.com") conn=net.createConnection(net.TCP, 0) conn:on("receive", function(conn, payload) print(payload) end) -- api.thingspeak.com 184.106.153.149 conn:connect(80,'184.106.153.149') conn:send("GET /update?key=Q67WTIRSOWGXJEO&field1="..t1.." HTTP/1.1\r\n") conn:send("Host: api.thingspeak.com\r\n") conn:send("Accept: */*\r\n") conn:send("User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n") conn:send("\r\n") conn:on("sent",function(conn) print("Closing connection") conn:close() end) conn:on("disconnection", function(conn) print("Got disconnection...") end) end -- send data every X ms to thing speak tmr.alarm(0, 60000, 1, function() sendData() end )
Run and enjoy.
The lua-scripts are in github.
When I try this Lua reports:
ds18b20-B.lua:1: module ‘ds18b20’ not found:
no field package.preload[‘ds18b20’]
no file ‘ds18b20.lua’
no file ‘ds18b20.lc’
I’d appreciate some guidance as to how to fix it.
You will need to first upload the ds18b20.lua to ESP. https://github.com/nodemcu/nodemcu-firmware/blob/master/lua_modules/ds18b20/ds18b20.lua
Hi, I would like to first thank you about sharing this nice topic.
Do you have any idea regarding hte battery life. ?
Cheers
The code as-is is not optimized in any way to preserve energy. Running it with a powerbank containing 2*2800mAh 3.7v lithium cells it did run for 5 days. With those AA-batteries it depends on the batteries but I would say something along the same lines. I never did prolonged testing with that code and AA-batteries.
code does notwork with negative temperatures below 0
Might be true. Feel free to fix it and publish the outcome. The example code is used for indoor temperature logging so no testing with negative temperatures.
Pystyykö tuohon kytkemään useamman ds18b20 anturin?
I looked the code at https://github.com/nodemcu/nodemcu-firmware/blob/master/lua_modules/ds18b20/ds18b20.lua and came up with thought that other free GPIO-pins could be used too. To the script of the previous link should be just programmed a little loop where each 1-wire sensor (DS18B20) coupled to a GPIO-pin are read in a sequence.
Other option is to use ESP8266-piirin I2C-bus driver implementation (https://github.com/zarya/esp8266_i2c_driver/blob/master/i2c.c), with 8-channel 1-wire master chip: http://www.maximintegrated.com/en/products/interface/controllers-expanders/DS2482-800.html
Kiteyttäen: Yksi anturi per GPIO-pinni vaikuttaa mahdolliselta, mutta linkin koodi vaatisi ihan pienen muutoksen. En osaa varmaksi sanoa toimisiko. Tuossa 8-pinnin ESP-01 moduulissa on vain 2 GPIO-pinniä vedetty eli maksimissaan 2 anturia voisi mahdollisesti kytkeä. Toinen vaihtoehto on käyttää I2C-ajuria ja kytkeä siihen DS2482-800-piiri, jolla voisi lukea 8 eri DS18B20-anturia. I2C-ajuri vaikuttaa kuitenkin vielä hieman keskeneräiseltä.
Löytyy myös malli, josta ovat kaikki pinnit vedetty asiallisesti: http://www.ebay.com/itm/ESP8266-Serial-Port-Module-Send-Receive-IO-Lead-Out-WIFI-Wireless-Transceiver/291365156923?_trksid=p2047675.c100005.m1851&_trkparms=aid%3D222007%26algo%3DSIC.MBE%26ao%3D1%26asc%3D28808%26meid%3D667fa83ad868420cbd7a2a687822e66b%26pid%3D100005%26rk%3D1%26rkt%3D6%26sd%3D301445049284&rt=nc
Pinout-kuva löytyy: http://tech.scargill.net/wp-content/uploads/2015/01/esp-201.jpg , jossa on 8 GPIO-pinniä.
already opened a github issue for this:
https://github.com/nodemcu/nodemcu-firmware/issues/232
Nice write-up. But I have a problem. When I run the above Lua program I am getting “attempt to index global ‘ds18b20’ (a nill value). Any idea why?
I’ve got the same error, but are too new to Lua to solve the problem. I’ve found some hints in http://www.factorioforums.com/forum/viewtopic.php?f=25&t=17107 bit were not able to translate it into a working ds18b20 temperature reading script.
Lua 5.1.4
Do you have a solution?
There is now a new tutorial with ArduinoIDE and thus skipping the problems with lua. ArduinoIDE can be used with ESP01 also. https://vaasa.hacklab.fi/2016/02/06/esp8266-on-nodemcu-board-ds18b20-arduinoide-thingspeak/
If I’m not mistaken the DS18B20 is drawn as a mirror image of the actual package in both images. The pin names are correct though; the resistor is and should be a pullup. Note that it can also be run in parasitic mode by tying VDD to GND.
Image now fixed.
Really nice article!
I’m getting “Got disconnection…” every time it tries to connect to thingspeak.
It is connected to my network and gets a ip but for some reason it does not upload any data.
I have set up my api keys properly.
Do you have any ideas what I could try?
———– serial log
=wifi.sta.getip()
10.101.29.125
> Temp:26 C
Sending data to thingspeak.com
Closing connection
Got disconnection…
———–
Hi, I have the same problem, it seams that the ds18b20 is read properly, if I hold the sensor, the temp reported goes up, but, as yours, it does not save to thingspeak. I tested with same API key in a browser from my computer, and that works. So I assume that the ESP-03 is not getting to send over internet to thingspeak.
=====dallas.lua reports the following: ======
Temp:33.5 C
Sending data to thingspeak.com
Got disconnection…
=====whilst the wifi.sta.getip() reports, thus I assume all okay with wifi settings, and I can ping it=====
> =wifi.sta.getip()
192.168.2.61 255.255.255.0 192.168.2.1
=========
Does anybody have an idea on where I must look?
I also tried another s1820.lua solution on git, and have the same issue, thus suspecting esp-03 not getting onto internet ???
There is now updated tutorial on using ESP8266 and with ArduinoIDE. It might be easier to try that approach and get rid of the lua related problems. https://vaasa.hacklab.fi/2016/02/06/esp8266-on-nodemcu-board-ds18b20-arduinoide-thingspeak/
In your diagram the DS18B20 is drawn the wrong way round!! My DS18B20 got really hot when i connected it like in your diagram.
Please correct the image!
The schematics was correct all the time. The part was just errorneous in the parts library of Fritzing and thus produced a faulty image with pin orders. Now fixed. Never trust computers.
Hey thanks for creating this guide! I followed your instructions and it works great. Like some have already mentioned the picture shows the DS18B20 pins reversed but that was easy to correct. Now that I have the temperature posting to thingspeak I was wondering if you know how to modify the code to display F instead of C. Again thanks for sharing your work!
Chris,
I used this little function to do that in my dht11 module.
local function toFahrenheit(c)
return c * 9 / 5 + 32
end
just apply the math and bam!!! Fahrenheit 🙂
Now fixed the image with a fixed part for Fritzing with right pin-order in the fancy looking breadboard picture also.
Just a question;
You are doing this in your code:
t1=ds18b20.read()
t1=ds18b20.read()
print(“Temp:”..t1..” C\n”)
You read the temperature twice,
is it because that you want to avoid the reset value that is 85°C?
Now that you say that.. I have no idea why it is read twice. But maybe the reason is as you stated to skip the 85C. Or could it be just a typo on cleaning up the code and thus multiplication of a line there.
Nice write-up thanks. I got 85C result before it was called twice – then I got 20C correctly, so it appears it is needed.
Why there is resistor between DQ and VDD ?
The resistor is a pull-up resistor for the data line. This insures that a reliable stream of 1’s and 0’s come out of the sensor.
There are several examples on the Internet where there is no resistor. The data stream relies on a ‘parasitic’ voltage for the data stream, which usually works, but not always.
Can you explain the code:
conn:on(“sent”,function(conn)
print(“Closing connection”)
conn:close()
end)
Is this checking to make sure the send has worked?
I suspect the 85C / 20C 2 reads is because of not enough delay after issuing a convert cmd to the ds18b20, if the DS18b20 is operating in parasite mode [ no +5Volts] then need to delay 750Ms+
I’m not sure how much delay is needed if using non parasite- see data sheet
Have all 3 LUA files on the device…
Am using the “fixed for negative values” of ds18b20.lua from here (https://github.com/sza2/nodemcu-firmware/commit/5a629e429752c5f99d1233cb133bdf614fb7d7c0) as Im wanting to use this as a freezer temp monitor.
Running the files on the ESP8266 using ESplorer, I get the following:
error loading module ‘ds18b20’ from file ‘ds18b20.lua’:
ds18b20.lua:11: ‘=’ expected near ‘local’
Line 11 is
“local modname = …”
direct from the original file.
Is “…” correct, or am I supposed to change this to something?
FWIW, this is running direct from the programmer usb doodah – I dont have the resister / temp chip on the board yet… just wanted to see if the script ran ok before I take it out of scripting mode for the final build.
Thanks 🙂
Hi, thanks for your help in writing this code.
I am trying to implement this example with en ESP8266 dev board, and I’m getting this message :
Config done, IP is 192.168.0.25
PANIC: unprotected error in call to Lua API (error loading module ‘ds18b20’ from file ‘ds18b20.lua’:
ds18b20.lua:114: malformed number near ‘1.8’)
Any idea on what’s going wrong ? Thanks in advance for your support !
The ds18b20.lua seems to be updated a lot after this tutorial. Make sure you have enough spaces around there at that line. Get rid of the Fahrenheit stuff? Try with older version of ds18b20.lua? From google there are words about locale specific separators. https://github.com/mason-larobina/luakit/issues/143
It’s all about the decimal separator and locale, but to change locale you call os.setlocale() and os is not available in nodemcu aparently…
If anyone can find a solution cuz this seems like a big issue (all decimal literals broken)
There is now updated tutorial that is using ArduinoIDE, https://vaasa.hacklab.fi/2016/02/06/esp8266-on-nodemcu-board-ds18b20-arduinoide-thingspeak/
It looks like it is about locale and the way 1.8 is interpreted. Locale specific variant could be 1,8. I have no idea on how to solve that but the ways to figure is out are in the mason-larobina github issue linked.
Hi, I’m trying to use same code, but when execute ” t.setup(gpio0) ” i see:
attempt to index global ‘t’ (a boolean value)
I think my ” t = require(“ds18b20″) ” doesnt work, but ds18b20.lua and ds18b20.lc are exist…
This is one of the reasons why the new tutorial is done with Arduino IDE. It just works. Lua seems to be a bit too much dependent on operating system and other settings. This is related to your problem actually, http://stackoverflow.com/questions/27458453/attempt-to-index-local-a-boolean-value
Hmm… Thanks.
I’m first time use lua and arduino will be complicated too…
Is it possible to avoid “require” by replacing read functions to main script?
ArduinoIDE is pretty simple approach https://vaasa.hacklab.fi/2016/02/06/esp8266-on-nodemcu-board-ds18b20-arduinoide-thingspeak/
http://stackoverflow.com/questions/15988268/calling-functions-on-required-modules-in-lua-gives-me-attempt-to-index-local