Browse Source

PWM fadein and fadeout. Server.

etisab 9 years ago
parent
commit
f02a4aef99
2 changed files with 82 additions and 14 deletions
  1. 7 10
      init.lua
  2. 75 4
      main.lua

+ 7 - 10
init.lua

@@ -1,17 +1,14 @@
 DEBUG = true
 
 function debug_message(message)
-  if DEBUG
+  if DEBUG then
     print(message)
   end
 end
 
-if DEBUG
-  print("Waiting one second on timer 0")
-  tmr.alarm(0, 1000, tmr.ALARM_SINGLE, 
-    function() 
-      dofile("main.lua")
-      end)
-else
-  dofile("main.lua")
-end
+print("Waiting one second on timer 0")
+tmr.alarm(0, 1000, tmr.ALARM_SINGLE, 
+  function() 
+    dofile("main.lua")
+  end)
+

+ 75 - 4
main.lua

@@ -1,6 +1,11 @@
 print("starting main.lua")
 
-local pin = 6
+local srv = nil
+local button_pin = 6
+local pwm_pin = 1
+local pwm_timer = 1
+local pwm_freq = 500
+local pwm_max_bright = 1023
 
 function debounce (func)
     local last = 0
@@ -16,8 +21,74 @@ function debounce (func)
 end
 
 function onChange ()
-    print('The pin value has changed to '..gpio.read(pin))
+    print('LYFT OFF!')
 end
 
-gpio.mode(pin, gpio.INT)
-gpio.trig(pin, 'both', debounce(onChange))
+function startServer()
+  debug_message('server start')
+  debug_message(srv)
+
+  if srv then
+    srv = nil
+  end
+  srv = net.createServer(net.TCP, 30)
+  srv:listen(80, connect)
+  debug_message(srv)
+end
+
+function stopServer()
+  debug_message('server stop')
+  debug_message(srv)
+  if srv then
+    srv:close()
+    srv = nil
+  end
+  debug_message(srv)
+end
+
+function connect(sock)
+  sock:on('receive', function(sck, payload)
+    conn:send('HTTP/1.1 200 OK\r\n\r\n' .. 'Hello world')
+  end)
+
+  sock:on('send', function(sck)
+    sck:close()
+  end)
+end
+
+function onStart()
+  debug_message('onStart')
+
+  -- register PWM and set low
+  -- tmr.unregister(pwm_timer)
+  pwm.setup(pwm_pin, pwm_freq, 0)
+  pwm.start(pwm_pin)
+  -- pwm.stop(pwm_pin)
+end
+
+function pwm_fadein()
+  local brightness = pwm.getduty(pwm_pin)
+
+  if brightness >= pwm_max_bright then
+    tmr.unregister(pwm_timer)
+  else
+    pwm.setduty(pwm_pin, brightness + 1)
+    tmr.alarm(pwm_timer, 2, tmr.ALARM_SINGLE, pwm_fadein)
+  end
+end
+
+function pwm_fadeout()
+  local brightness = pwm.getduty(pwm_pin)
+
+  if brightness <= 0 then
+    tmr.unregister(pwm_timer)
+  else
+    pwm.setduty(pwm_pin, brightness - 3)
+    tmr.alarm(pwm_timer, 2, tmr.ALARM_SINGLE, pwm_fadeout)
+  end
+end
+
+onStart()
+startServer()
+gpio.mode(button_pin, gpio.INT)
+gpio.trig(button_pin, 'both', debounce(onChange))