So my ESP8266 modules finally arrived just in time for a quick project.
The problem, my parents that live up north are heading out of town for a while and to calm my fathers nerves he would like to know if the house gets below freezing. I thought I would whip up a quick wireless thermometer for him as my first ESP8266 project.
First I couldn’t be bothered to build my own firmware for this so instead I used this lua firmware. My project is simple enough so I felt this would do the trick.
To program this firmware I used esptool.py to upload the custom firmware on to the device using a 3.3v usb to serial adapter. Note GPIO 0 needs to be set to low to enable firmware update mode.
./esptool.py -p /dev/<path-to-serial> write_flash 0x000000 nodemcu_512k.bin
Firmware now updated I can connect via serial to see if wifi is working:
> wifi.setmode(wifi.STATION);
> wifi.sta.config("<ssid>","<password>");
> print(wifi.sta.getip());
192.168.0.120
Success! I’m connected.
Using a MCP9808 I connected this i2c temperature sensor to GPIO pins 0 and 2 on the wifi module, to read the values I used this:
id=0
sda=9 --GPIO2
scl=8 --GPIO0
i2c.setup(id, sda, scl, i2c.SLOW)
function read_reg(dev_addr, reg_addr)
i2c.start(id)
i2c.address(id, dev_addr ,i2c.TRANSMITTER)
i2c.write(id,reg_addr)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr,i2c.RECEIVER)
c=i2c.read(id,2)
i2c.stop(id)
return c
end
tempval = read_reg(0x18, 0x05)
This gives me a 2 byte value of the current temperature and since I have no idea how to bit shift in lua I thought I would just send both byte values to one of my servers running node.js to process.
conn=net.createConnection(net.TCP, 0)
conn:connect(300 0,"<hostname>")
payload = "{\"current\":[" .. string.byte(tempval,1) .. "," .. string.byte(tempval,2) .. "]}";
conn:send("PUT /<uri> HTTP/1.1\r\n"
.."Host: <hostname>\r\n"
.."Content-Type: application/json\r\n"
.."Content-Length: " .. payload:len() .. "\r\n"
.."Connection: close\r\n"
.."\r\n"..payload.."\r\n")
Data is sent. Since everything is looking good I wrapped the read_reg and upload in a function then ran this on a timer to execute every 20 seconds. Now when my parents want to see the temperature they can view the webpage and see the current temp and historic chart.
All that is left for this is to add a voltage regulator and some sort of power source and it’s ready to go.