Tag Archives: ESP8266

ESP8266 IOT Controller

Flashing ESP Modules with Arduino IDE

If you want to flash new firmware onto your ESP8266 module GPIO 0 has to be connected to GND during powering up the module. Normally you would do that with a jumper wire or a little switch. Of course it would be good if it could be so comfortable like with an Arduino where you just press the upload button in the IDE and the controller is flashed.

But luckily this is possible as well with the ESP. Therefore 2 additional signals from the FTDI USB Serial adapter are used – RTS and DTR. On The github project page there is a schematics how the ESP module has to be connected to the USB serial adapter. I found out that the nodemcu-devkit modules already work out of the box. They can be purchased for less then 10€ on ebay.For other modules like the ESP01 module you can build your own adapter.

ESP_to_serial

The schematics is mentioning a separate 3.3v power supply. I noticed that at least the FTDI USB serial converter I am using is capable to supply enough power to flash and test a ESP01 module. Since GPIO15 is not exposed on an ESP01 module I have only connected the upper 3 10k resistors. 2 of them (REST and CH_PD) I have soldered directly to the module because they are more or less always needed. the one going from 3V3 to GPIO0 is in the adapter cable. The wiring is like this:

esp01-ftdi_bb

Make sure you set the voltage jumper to 3.3V !!!

Advertisements

ESP8266 with Arduino IDE

It has been a while since I had time to write something here. But there is one thing which I found last week, which should be mentioned here. There is a great project on github which adds support for the ESP8266 to the standard Arduino IDE. This is good news because there are so many examples and projects for Arduino boards on the net which now can be used with the ESP8266 as well. Basically the ESP is now like any other Arduino board. To get this working you have to install the Arduino IDE on your computer. It will work on Linux OSX and Windows. In order to work with the ESP you will have to use the 1.6.x version. You can get it from the Arduino download page. I have tested it with the 1.6.5 version under OSX and Windows. Installing support for new boards is very easy.

  • Open in the menu the Preferences and past the following URL at the field “Additional Boards Manager URLs:”
    http://arduino.esp8266.com/stable/package_esp8266com_index.json
    esp-arduino-1
  • Press OK
  • Open Tools -> Board -> Boards Manager
  • At the Type drop down select Contributed
  • Now you should see a section for the esp8266 – klick on it and press Install. This will download everything you need and you are done with the installation

If the steps above have worked you can now select several ESP8266 based boards. If you do not have any of the mentioned boards you can always select Generic ESP8266 board.

There are also some examples which can be found on the github page as well. General information can be found on the homepage of the project.

ESP8266 as a WEB server

Since the ESP firmware has a complete IP stack it can also act as a server in an IP network. Of course you will not be able to run a full featured WEB server on such a device. But that is also not necessary to do some useful tasks.

If you want to do some home automation – web services are a simple way to connect things together. In my example I have a little web server which controls a GPIO pin of the ESP. You can turn it on an off and ask for the current state. To add some security also have to submit a PIN as well. If you want to make sure that your home automation is save you should run all components in a separate WLAN. The script will do the following.

If you do not use the right pin the TCP connection is closed without any response. This example can easily extended to control more pins or display values from sensors.

-- script will start a http server on http_port
-- requests do look like
-- http://espmodule.domain/?PIN=1234&switch=ON
-- PIN is just a little bit of security to avoide someone playing around
-- switch=ON will turn switch_pin to high
-- switch=OFF will turn switch_pin to low
-- switch=status will just print ON or OFF

switch_pin   = 0         -- ESP pin to be controlled
switch_state = "OFF"     -- initial state
PIN          = "1234"    -- pin code 
http_port    = 80        -- port of http server
module_name  = "kitchen" -- just give the module a name

gpio.mode(switch_pin, gpio.OUTPUT)
gpio.write(switch_pin, gpio.LOW)

-- deliver static content (just to make the code more readable)
function page(what)
 local content = ""
 if what == "start" then --httppage header
  content = content .. "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n"
  content = content .. "\"http://www.w3.org/TR/html4/loose.dtd\">\n"
  content = content .. "<html>\n<head>\n<title>NODE MCU TEST</title>\n</head>\n<body>\n"
  content = content .. "<h1>ESP8266 module "..module_name.."</h1>\n"
  end
 if what == "end" then --close http page
  content = content .. "</body>\n</html>"
 end
 return content
end

--define what is happening if server is contacted
server = net.createServer(net.TCP) 
server:listen(http_port,function(conn) 
 conn:on("receive", function(client,request)
  -- this code block gets the params of the http request und stores that in params
  local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
  if(method == nil)then 
   _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP"); 
  end
  local params = {}
  if (vars ~= nil)then 
   for param, value in string.gmatch(vars, "(%w+)=(%w+)&*") do 
    params[param] = value
   end 
  end
  -- now the code which is doing something based on the request
  if params.pin == PIN then
   local message = ""
    if(params.switch == "ON")then
     message = "<h1>Turning switch ON</h2>\n";
     gpio.write(switch_pin, gpio.HIGH);
     switch_state = "ON"
    elseif(params.switch == "OFF")then
     message = "<h1>Turning switch OFF</h2>\n";
     gpio.write(switch_pin, gpio.LOW);
     switch_state = "OFF"
    elseif(params.switch == "STATE")then
     message = "<h1>state: "..switch_state.."</h2>\n";
    end
    client:send(page("start")..message..page("end"));
   end
  client:close();
  collectgarbage();
 end)
end)

You can test with a normal web browser or on the command line. For instace with wget or curl.
It will look like this:

curl "http://espmodul.home/?pin=1234&switch=ON"

the response will be

ESP8266 module kitchen
Turning switch ON

Reading temperature and humidity from a DHT22 sensor

One use case for a ESP8266 module is measuring temperature and humidity. On very common sensor is the DHT22. You can get if for about 4-5$ at eBay. Because it has only one data pin an ESP-01 module would be good enough. The DHT22 is also supported out of the box the module you need can be found in the nodemcu firmware under lua-modules/dht22/dht22.lua.

The example below will only work with the floating point version of the nodemcu software correctly. The integer version will only show the integer part of the values.

-- This script will read temperature and humidity from a DHT22 sensor
-- Use the floating point version of the nodemcu firmware
PIN = 2 -- data pin of DHT22
dht22 = require("dht22") --can be found in nodemcu from GitHub under lua-modules/dht22/dht22.lua
dht22.read(PIN)
temperature = dht22.getTemperature()/10 -- DHT22 module returns integer of 0.1 deg C
humidity = dht22.getHumidity()/10 -- DHT22 module returns integer of 0.1 %
if humidity == nil then
 print("Error reading from DHT22")
else
 -- temperature in degrees Celsius
 print("Temperature: "..temperature.." deg C")
 -- humidity
 print("Humidity: "..humidity.."%")
end
-- release module
dht22 = nil
package.loaded["dht22"]=nil

dht22

Just connect pin 1 to 3.3V, pin 2 to the ESP data pin and pin 4 to GND. Pin 3 is unused.

init.lua

After you have successfully flashed the nodemcu firmware and your IDE is running. It is important to tell the ESP module what to do after power on.

The nodemcu firmware is trying to execute a file called init.lua. You can of course name your script always init.lua but then you are limited to one filename, which might be confusing :-).

One thing which always need to be done is the configuration of the WIFI networking. That’s why I have created an init.lua file which does that and executes another LUA script after that is done. You can choose to put your module in station mode (when it’s suposed to be part of an existing WLAN) or the module can be an access point (then it creates it’s own WLAN.

-- This script is automaticaly executed during startup of the module
-- It will either configure the module to be an Access Point or a Station in an existing WLAN and start another LUA scrip

mode = "ap" -- define the WIFI mode Station or Access Point
startup = "test.lua" -- which main script gets executed after network config is done
SID = "test" -- define SID
password = "12345678" -- define the password

print("starting in "..mode.." mode")

-- configute the module to ba an access point with SID and password
-- after that start the script defined in startup
if mode == "ap" then
 wifi.setmode(wifi.SOFTAP);
 wifi.ap.config({ssid=SID,pwd=password});
 print("ESP8266 mode is: " .. wifi.getmode())
 print("The module MAC address is: " .. wifi.ap.getmac())
 print("Config done, IP is "..wifi.ap.getip())
 dofile(startup)
end

-- configure the module to join the existing network with SID and password
-- It will wait until the module gets an IP from the router with DHCP
-- after that start the script defined in startup
if mode == "station" then
 wifi.setmode(wifi.STATION);
 wifi.sta.config(SID,password)
 wifi.sta.connect()
 tmr.alarm(1, 1000, 1, function()
  if wifi.sta.getip()== nil then
   print("IP unavaiable, Waiting...")
  else
   tmr.stop(1)
   print("ESP8266 mode is: " .. wifi.getmode())
   print("The module MAC address is: " .. wifi.sta.getmac())
   print("Config done, IP is "..wifi.sta.getip())
   dofile(startup)
  end
 end)
end

Writing LUA code fore ESP8266 nodemcu firmware

Things you need

  • First you need to install nodemcu firmware on the ESP module – please see my other posts how to do that.
  • Connect your ESP to your PC using a USB/serial converter with 3.3V signal level (see my other post).
  • Power the ESP module with 3.3V – never 5V.
  • There is a JAVA based IDE for the ESP8266. It’s called ESPlorer.
    ESPlorer-screen
    You can get the tool here. It allows you to edit your scripts with syntax highlighting, upload and execute them, execute single commands and many other useful things. If you should have problems when uploading your scripts you can disable the “Turbo mode” in the settings TAB. For me that helped a lot. I have tested the ESPLorer on OSX, Windows and Debian Linux. You need a JAVA 7 runtime to start it.

Things you should read

There are man examples and projects on the internet. If you have time, you can get some inspiration for your own projects. The best place to start ist the nodemcu API reference page.

Flashing new firmware onto ESP8266

When you get your ESP module it has most likely the default AT firmware installed and even this is not up to date. That’s why the first Thing you want to do is upgrading firmware.

There is the the so called AT firmware, which is the default one. This can be used fore instance together with an Arduino. The best source I fount for this firmware is linked on this page.

If you want to write your own code in LUA you should use the modified software which comes from the open source project nodemcu.

If you want you can cross compile your own firmware out of the source. So fare I have not taken the time to do this. It is also possible to download pre built firmware images which are not too far behind the latest source code. The download page is here. There are 2 versions one is the integer version the other one is the floating point version. I am always using the floating point version. It is slightly bigger but better if you need to deal with floating point values.

To flash the firmware you can use a python based esptool tool which I have tested on OSX and linux. If it works on Windows as well I cannot tell. For windows there is also a special tool – nodemcu-flasher – but I have never used it.

It is important that you need to connect GPIO 0 of the ESP-Module to GND before you power the module on. That will put the module in a special mode which allows you to flash the firmware. With esptool you would do the following:

  • get esptool.py
  • download firmware image (the *.bin file)
  • connect GPIO 0 to GND
  • toggle power
  • execute the following command:
/path-to-esptool/esptool.py -p /dev/serial-device write_flash 0x000000 /path-to-firmware/firmware-file.bin
  • wait until it’s finished
  • disconnect GPIO 0 from GND
  • toggle power

Now you can connect to the ESP chip using a serial terminal program (9600 8 N 1 – no local echo). Make sure that you configure the terminal to send CR and LF after pressing enter.

To test if LUA the firmware is active you can enter:

print("123") <ENTER>

It should print 123 😉