Posting to Thingspeak with ESP8266 and NodeMCU

This is just a short post to show some code to post to Thingspeak from an ESP8266 running NodeMCU.

The code only post to field1, but can easily get updated to post to multiple fields at the same time. To test this, you don’t need any extra sensors, because the example is just posing the internal voltage reading.

Only thing needed to be changed, is the “CHANNEL_API_KEY”, which you can find on the Thingspeak page after creating your channel, and the WiFi credentials.

wifi.setmode(wifi.STATION);
wifi.sta.config("SSID" ,"WIFIKEY");

function postThingSpeak(level)
	connout = nil
	connout = net.createConnection(net.TCP, 0)

	connout:on("receive", function(connout, payloadout)
		if (string.find(payloadout, "Status: 200 OK") ~= nil) then
			print("Posted OK");
		end
	end)

	connout:on("connection", function(connout, payloadout)

		print ("Posting...");

		local volt = node.readvdd33();		

		connout:send("GET /update?api_key=CHANNEL_API_KEY&field1=" .. (volt/1000) .. "." .. (volt%1000)
		.. " HTTP/1.1\r\n"
		.. "Host: api.thingspeak.com\r\n"
		.. "Connection: close\r\n"
		.. "Accept: */*\r\n"
		.. "User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n"
		.. "\r\n")
	end)

	connout:on("disconnection", function(connout, payloadout)
		connout:close();
		collectgarbage();
	end)

	connout:connect(80,'api.thingspeak.com')
end

tmr.alarm(1, 60000, 1, function() postThingSpeak(0) end)

15 comments

Leave a Reply