Tuesday, October 4, 2016

Controlling RGB LED on Witty NodeMCU ESP8266 Device

This is code to control the LED that's on the Witty NodeMCU ESP8266 Device. It seems to be a basic RGB LED rather than a fancy WS2812 LED.

-- Debug LED led.lua
--local M = {} 
M = {} 
M.pinR = 8  -- gpio 15
M.pinG = 6  -- gpio 12
M.pinB = 7  -- gpio 13
M.isOnR = false
M.isOnG = false
M.isOnB = false
M.isInitted = false

function M.init()
  if M.isInitted then return end
  -- setup led as output and turn on
  gpio.mode(M.pinR, gpio.OUTPUT)
  gpio.mode(M.pinG, gpio.OUTPUT)
  gpio.mode(M.pinB, gpio.OUTPUT)
  M.isInitted = true
  print("Initted LED pins")
end

-- RED 

function M.onR()
  M.init()
  gpio.write(M.pinR, gpio.HIGH)
  M.isOnR = true
  print("Turned LED Red on. pin: " .. M.pinR)
end

function M.offR()
  M.init()
  gpio.write(M.pinR, gpio.LOW)
  M.isOnR = false
  print("Turned LED Red off. pin: " .. M.pinR)
end

function M.toggleR()
  if M.isOnR then
    M.offR()
  else
    M.onR()
  end
end

-- GREEN

function M.onG()
  M.init()
  gpio.write(M.pinG, gpio.HIGH)
  M.isOnG = true
  print("Turned LED Green on. pin: " .. M.pinG)
end

function M.offG()
  M.init()
  gpio.write(M.pinG, gpio.LOW)
  M.isOnG = false
  print("Turned LED Green off. pin: " .. M.pinG)
end

function M.toggleG()
  if M.isOnG then
    M.offG()
  else
    M.onG()
  end
end

-- BLUE 

function M.onB()
  M.init()
  gpio.write(M.pinB, gpio.HIGH)
  M.isOnB = true
  print("Turned LED Blue on. pin: " .. M.pinB)
end

function M.offB()
  M.init()
  gpio.write(M.pinB, gpio.LOW)
  M.isOnB = false
  print("Turned LED Blue off. pin: " .. M.pinB)
end

function M.toggleB()
  if M.isOnB then
    M.offB()
  else
    M.onB()
  end
end

--return M 
led = M

--tmr.alarm(0, 1000, tmr.ALARM_AUTO, led.toggleR)
--tmr.alarm(1, 2000, tmr.ALARM_AUTO, led.toggleG)
--tmr.alarm(2, 4000, tmr.ALARM_AUTO, led.toggleB)

function M.fadeInR()
  pwm.setup(M.pinR, 1000, 0)
  --pwm.setclock(1000)
  local cl = pwm.getclock(M.pinR)
  print("Freq of Red pin:" .. cl)
  local duty = pwm.getduty(M.pinR)
  print("Duty of Red pin:" .. duty)
  pwm.start(M.pinR)
  
  --for i = 1,1023 do
  --  pwm.setduty(led.pinR, i)
  --end
  
  tmr.alarm(0, 1, tmr.ALARM_AUTO, M.fadeInIncrementR)
  
  --pwm.stop()
end

function M.fadeInIncrementR()
  local duty = pwm.getduty(M.pinR)
  duty = duty + 1
  pwm.setduty(led.pinR, duty)
  if duty == 1023 then
    tmr.stop(0)
    tmr.unregister(0)
    M.fadeInR()
  end
end

M.offG()
M.offB()
M.fadeInR()

No comments:

Post a Comment