Last active
April 10, 2017 05:07
-
-
Save hanshuebner/ec998b0a86b59e8405404838f6328524 to your computer and use it in GitHub Desktop.
NodeMCU program to read buttons and light up LEDs, communicates with MQTT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
broker_ip_address='192.168.178.19' | |
wifi.sta.config({ssid="ssid",pwd="password"}) | |
m = mqtt.Client('esp', 120, 'dev', 'dev') | |
wifi.setmode(wifi.STATION) | |
gpio.mode(1, gpio.INPUT, gpio.PULLUP) | |
gpio.mode(2, gpio.INPUT, gpio.PULLUP) | |
gpio.mode(3, gpio.OUTPUT, gpio.PULLUP) | |
gpio.mode(4, gpio.OUTPUT, gpio.PULLUP) | |
m:on("message", function(client, topic, data) | |
print("got message: " .. topic) | |
local _, _, led, state = string.find(topic, 'vote.led.([0123]).(%a+)') | |
if state == 'on' then | |
gpio.write(led + 3, 0) | |
elseif state == 'off' then | |
gpio.write(led + 3, 1) | |
else | |
print("message could not be parsed") | |
end | |
end) | |
function connect_to_broker() | |
m:connect(broker_ip_address, | |
1883, 0, | |
function(client) | |
m:subscribe('vote/led/#', 0, function() print('subscribed to led messages') end) | |
end, | |
function(client) | |
print('connection to message broker failed') | |
end) | |
end | |
key_pins = { 1, 2, 5, 6 } | |
key_state = { 1, 1, 1, 1 } | |
keyboard_timer = tmr.create() | |
keyboard_timer:register(100, tmr.ALARM_AUTO, function () | |
for i, pin in ipairs(key_pins) do | |
local new_state = gpio.read(pin) | |
if new_state ~= key_state[i] then | |
print("key " .. i .. " state " .. new_state) | |
key_state[i] = new_state | |
if new_state == 1 then | |
m:publish("vote/keypress/" .. i, '', 0, 0) | |
end | |
end | |
end | |
end) | |
keyboard_timer:start() | |
wait_led_state = 0 | |
netup_timer = tmr.create() | |
netup_timer:register(150, tmr.ALARM_AUTO, function () | |
ip_address = wifi.sta.getip() | |
if ip_address == nil then | |
gpio.write(3, wait_led_state) | |
wait_led_state = wait_led_state == 1 and 0 or 1 | |
else | |
gpio.write(3, 1) | |
netup_timer:stop() | |
print("IP address: " .. ip_address) | |
connect_to_broker() | |
end | |
end) | |
netup_timer:start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment