Print Friendly, PDF & Email

Components Required:

1. NodeMCU DEVKIT – 2 – Buy

2. Linux PC/Windows PC (Tested with Windows 10, Ubuntu 14.04 LTS)

3. Micro USB cable – 2 – Buy

4. Potentiometer – 10K Ohm

5. 5 mm LED – Buy

Way to go ->

1. Connect NodeMCU DEVKIT to PC via the Micro USB cable.

2. Write the following scripts and upload to the first NodeMCU.

init.lua

wifi.setmode(wifi.STATION)
wifi.sta.config("wifi_name","wifi_password")
print(wifi.sta.getip())
dofile("ToThingSpeak.lua")

ToThingSpeak.lua

function postThingSpeak(level)
    local volt = adc.read(0)
    print ((volt / 1024) * 3.2)
    local connout = nil

    connout = net.createConnection(net.TCP, 0)
    connout:connect(80,'api.thingspeak.com')
 
    connout:on("connection", function(connout, payloadout)
        print ("Posting...");
        connout:send("GET /update?api_key=Write_API_Key&field1=" .. ((volt/1024) * 3.2)
        .. " 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")
        print("Data Sent")
    end)

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

-- Post to ThingSpeak every 15 seconds 
tmr.alarm(1, 15000, 1, function() postThingSpeak(0) end)

3. Write the following the scripts and upload to the second NodeMCU.

init.lua

wifi.setmode(wifi.STATION)
wifi.sta.config("wifi_name","wifi_password")
print(wifi.sta.getip())
dofile("TSControl.lua")

TSControl.lua

led1 = 7
led2 = 4 -- onboard LED, active low i.e. ON -> 0, OFF -> 1 

gpio.mode(led1, gpio.OUTPUT)
gpio.mode(led2, gpio.OUTPUT)

function RemoveHeaders()
	http.get("https://api.thingspeak.com/channels/your_Channel_ID/fields/1/last?key=Read_API_Key", nil, function(code, data)
    if (code < 0) then
      print("HTTP request failed")
    else
      print("Voltage = " .. data .. " V")
      Control(data)
    end
  end)
end

function Control(data)
	number = tonumber(data)
	if (number > 1 and number < 2) then
		gpio.write(led1, 1)
		gpio.write(led2, 0)
	else
		gpio.write(led1, 0)
		gpio.write(led2, 1)
	end
end

-- every 1 second, check ThingSpeak
tmr.alarm(0, 1000, 1, function() RemoveHeaders() end)

Hardware Connections ->

1. LED to NodeMCU

2. Potentiometer to NodeMCU