Showing posts with label BT137. Show all posts
Showing posts with label BT137. Show all posts

Thursday, May 7, 2015

MPDMv3 - WIFI Mains Power Dimmer / Switch - Web Interface



----------------------------------------------------------------------------------------------------------------------------


WARNING!! You will play with LIVE MAINS!! Deadly zone!! 


      If you don't have any experience and are not qualified for working with MAINS power I will not encourage you to play arround!. The author take no responsibility for any injury or death resulting, directly or indirectly, from your inability to appreciate the hazards of household mains voltages.
   The circuit diagrams are as accurately as possible, but are offered with no guarantees whatsoever. 
    There is no guarantee that this design meets any Rules which may be in force in your country so please check before your local rules/regulations.

----------------------------------------------------------------------------------------------------------------------------  

     For any new requests please feel free to use as usual: tech at esp8266-projects.com.
 
     If you want to order MAINS POwer Dimmer/Switch bare PCBs only, you can also do it directly at Dirty PCBs, our preferred PCB House:

-----------------------------------------------------------------------------------------------------------------------------


     As I promised in the last article about the new MAINS Dimmer / Switch Module, Today we will continue with designing the Web interface access.


      What we will need:  


MAINS Power Dimmer / Switch Module - MPDMv3 - Connections



CBDB Evolution DevBoard


     Because I don't like to have flying MAINS wires on my workdesk I have created a temporary separate MPDMv3 Module Box, containing all the MAINS part of the story :).

Isolated MAINS unit - keep your fingers away from the Deadly zone !


      Remember, Safety First! And also more relaxing knowing that is no Russian Roulette wire game on progress on my table. Shit happens all the time, but at least let's try to reduce the chances to hit badly the fan too often :)


Live Testing on progress

   In the Box above is enough space for all the parts going inside, including ESP8266 module, power supply, Dimmer Module, Choke, etc, but at this stage I find it easier to connect them together like that.



MPDMv3 Web Server Software

For programming CBDBv2 Board and uploading the driver and the software we will continue to use the LuaUploader as before. 


1. Define used GPIO pin
:

      outpin=7                                                       -- Select Triac Command pin - GPIO13
      gpio.mode(outpin,gpio.OUTPUT)
      gpio.write(outpin,gpio.LOW)                       -- Triac OFF
      inpin=6                                                         -- Zero crossing detector input - GPIO12 
      gpio.mode(inpin,gpio.INT,gpio.PULLUP)   -- attach interrupt to ZCD





  2. Zero Cross Detector function and Triac command


      For a more detailed explanation how Zero cross detection circuit works please take a look at the previous MPDMv3 article.

      function zero_cross()
           dt = 76*dim
           --print("Zero cross detected!")
           stat = "ON"
           tmr.delay(dt)                                 -- Firing delay time calculated above
           gpio.write(outpin,gpio.HIGH)     -- Triac ON - Zero cross detected
           tmr.delay(100)                              -- Triac ON - Propagation time 
          gpio.write(outpin,gpio.LOW)        -- Triac OFF - let's be sure it's OFF before next cycle :)
          tmr.wdclr()
          return stat
     end




3. WEB Server

srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
   conn:on("receive", function(conn,payload)
      --debugging output only
      -- print(payload)
      if (string.find(payload, "GET / HTTP/1.1") ~= nil) then
         --print("GET received")
         sendPage(conn)
      else
         swstat={string.find(payload,"cmd=")}
         --If POST value exist, set power switch status
         if swstat[2]~=nil then
            --print("Command received: " .. payload)
            PwrSW(swstat,payload)
            sendPage(conn)
         end
      end
   end)
   conn:on("sent", function(conn)
      conn:close()
      conn = nil -- clear and allow the garbage collector to free the memory
      --print("Connection closed")
     
   end)
end)

 


4. Send page function based on received requests

function sendPage(conn)
   conn:send('HTTP/1.1 200 OK\n\n')
   conn:send("<META HTTP-EQUIV=\"REFRESH\" CONTENT=\"5\">")
   conn:send('<!DOCTYPE HTML>')
   conn:send('<html>')
   conn:send('<head><meta content="text/html; charset=utf-8">')
   conn:send('<LINK href="http://www.instructables.com/files/orig/FGU/L48I/I98BK1X6  

                       /FGUL48II98BK1X6.css"')
   conn:send('rel="stylesheet" type="text/css">')
   conn:send('<title>ESP8266 - Power Switch Controller</title></head>')
   conn:send('<body><center><h1>ESP8266 MAINS Power Dimmer Controller</h1></center>')
   conn:send('<br /><br />')
   conn:send('<form action="/" name="dimmer" oninput="outputUpdate(cmd.value)" 

                     method="POST">')
   conn:send('<font color=red><b>ON </b></font><input style="width:550px; height:50px" 

                     type="range" name="cmd" id="cmd" value="')
   conn:send(status)
   conn:send('" min=1 max=128 step=1 />')
   conn:send('<font color=red><b>OFF</b></font></form>')
   conn:send('<br><center>Dimmer Value: <b>')        
      conn:send(status)
      conn:send(' pts</b></center>')
   conn:send('<script type="text/javascript">')
   conn:send('function outputUpdate(dim) {document.querySelector("#cmd").value = dim;')
   conn:send('document.forms[0].submit();}</script>')
   conn:send('</body></html>')
end

 

 CSS file created for this example is just for fancy decorations. If you don't like it you can very easy change the style attributes or add local ones.



5. Check received Dimmer value and update status

     function PwrSW(swstat,payload)
           gpio.mode(outpin,gpio.OUTPUT)
           newstat=string.sub(payload,swstat[2]+1,#payload)
           status = tonumber(newstat)
           print("Dimmer Value:" ..  status)
    end






4. Main code

       status = 60                   -- around 50% - choose your desired start value.
       newstat = 60
        outpin=7                     -- Select Triac Command pin - GPIO13  
        gpio.mode(outpin,gpio.OUTPUT)
        gpio.write(outpin,gpio.LOW)  -- Triac OFF
        inpin=6                      -- Zero crossing detector input - GPIO12 
        gpio.mode(inpin,gpio.INT,gpio.PULLUP)  -- attach interrupt to ZCD
 

       gpio.trig(inpin,"up",zero_cross)                 -- ZCD interrupt attached - trigger on falling edge
       print(wifi.sta.getip())                                  -- print our new MPDMv3 WebServer IP



      For testing, just save the code on ESP as 'dimserver.lua', restart ESP and run:   
 
            dofile("dimserver.lua")      -- Start the Dimmer Listening WebServer
               =wifi.sta.getip()              -- find the IP Address where your Web Server will be

  

     Open your favorite Web browser and type your new MPDMv3 Web Server IP address. If all ok, should look something like below :

MPDMv3 Web Interface



If you want the MPDMv3 software to start automatically when your CBDB module starts or reboots, then you neet to create and add some lines in your 'init.lua' file:
  
          dofile("dimserver.lua")  -- Start automatically the Dimmer Listening WebServer



Save the code on ESP as 'init.lua', restart ESP. It should reboot and restart automatically the program.



A short video presentation, testing the Web Interface:





Friday, April 17, 2015

P2 - WIFI Web Power Switch for MAINS - MPSM v.2 DevBoard - ESP8266



UPDATE!! UPDATE !!

New released MPDMv4 (MAINS Power Dimmer) Driver Board !

 

--------------------------------------------------------------------------------------------------------------------------

WARNING!! You will play with LIVE MAINS!! Deadly zone!! 


If you don't have any experience and are not qualified for working with MAINS power I will not ecourage you to play arround!

---------------------------------------------------------------------------------------------------------------------------- 

    Remember the story about the WIFI MAINS Power Switch module? 

    Because of the high interest in the subject, a new dedicated Dev Board has been born:  MPSMv2, a small ESP8266 DevBoard with integrated MAINS Power Switch! 

   Yes, it's finally here, arrived safely from the PCB factory and you can see it below. I know a lot of you are waiting it already, but please be patient few more days. None of the already requested ones will leave the premises without a proper 24 hour test.
  
   For any new requests please feel free to use as usual: tech at esp8266-projects.com.
     If you want for your own experiments to order CBD v2 EVO bare PCBs only, you can also do it directly at Dirty PCBs, our preferred PCB House:


 
MPSM v2 Schematic


    Theory of operation remain the same so please take a look at the previous Article about MAINS Power Switch for deeper explanations.

     I don't know if this it's the smallest MAINS Power Switch with integrated WIFI and direct Web interface access but if is not, it's definitely closer to be at only around 25x50mm :)

MPSM v2 - PCB - TOP
    As you can see from the PCB picture above you have even a full ESP8266 pinout access thru 2 breadboard friendly expansion slots for future projects development.


   Finally,  the received result from the PCB Factory, a long awaited moment:

MPSM v2  PCB Batch


MPSM v2 - TOP


      If you want to have a separate Breadboard friendly ESP8266 adapter with integrated 3.3V Power Supply, you can cut the board in 2 independent working parts, the ESP07/12 adapter and the MAINS Triac Switch.

    It is designed in such way that no harm will be done by the cut to the functioning of the circuit. You can use the cut MAINS Power Switch part directly even with your ARM, PIC, Arduino, whatever MCU you like this days without any problems as long as it has a GPIO pin capable to drive the MOC Optocoupler LED.

MPSM v2  - separate usage ESP8266 adapter and MAINS Switch

ESP8266 ESP-07/12 Adapter



      And the final result, a fresh baked one, ready for testing:

MPSM v2 - full asembled


MPSM v2 - full asembled - bottom


-----------------------------------------------------------------------------------------------------------------
   Before going further and start running some tests few considerations to be done:
  • Do NOT use it without proper Knowledge about MAINS circuits !
  • Do NOT use it without a proper FUSE on MAINS line! 
  • This is NOT a Toy!
-----------------------------------------------------------------------------------------------------------------


     What we will need:
  • MPSM DevBoard from above
  • USB adapter (take a look on Part 1 for details how to connect them together)  
  • NodeMCU firmware (download latest - can use the floating point version for now) 
  • NodeMCU Flasher ( firmware programmer for NodeMCU DEVKIT) 
  • For programming MPSM v2 DevBoard and uploading the software we will continue to use the LuaUploader as before. 


    Flashing the MPSM NodeMCU Firmware is a straigth away process:
  
Programming MPSM v2 Board


  •  Connect MPSM Board with the USB Adapter, Set the PROG jumper (YELLOW) in the  Programming mode position (closed) and power on 
  • Start NodeMCU Flasher. Choose you USB adapter corresponding port
  • Add from Config Menu latest previously downloaded firmware. It must start from 0x0000. Disable anything else. 
  • Go back on Operation tab. Power off your MPSM Board. Press FLASH Button. power ON quick MPSM Board. It will be recognised and will start flashing. Give it a second try if necessary.
  • When finished succesfully A green OK checkmark will appear
  • Power Off   MPSM Board, Remove yellow jumper. Power back ON. A NodeMCU programmed MPSM Board is ready for action :)




    For a more detailed explanation for NodeMCU Firmware flashing please take a look at CBDB Board Firmware Flashing discussion



 To quick run a test we will use the code snippets provided by LuaUploader at start-up. Select the piece of code that you want to run and press "Execute Selection" button.


  • To quick setup your WIFI network - If this is your first project with a new ESP module that was never used in your WIFI Network, don't forget it - one time only :
            -- One time ESP Setup --
            wifi.setmode(wifi.STATION)
            wifi.sta.config ( "YOUR_WIFI_SSID" , "PASSWORD" ) 
            print(wifi.sta.getip())


  • For the Triac Optocoupler Command testing we will use the "Blinky" part of the code and if all ok it will blink LED2 with the choosen rate "dly".
          Run the modified code from below:

          -- Blink using timer alarm --
          timerId = 0 -- we have seven timers! 0..6
          dly = 500 -- milliseconds
          ledPin = 1 -- 1=GPIO5  - allocated pin for Triac opto command
          gpio.mode(ledPin,gpio.OUTPUT)
          ledState = 0
          tmr.alarm( timerId, dly, 1, function()
                ledState = 1 - ledState;
                 gpio.write(ledPin, ledState)
          end)




  Now you can connect you MAINS powered lightbulb and you can see it playing the "Blinky" game too :).  Use proper heatsink for power disipation for your Triac.


    Power Switch function and WEB Server software are the same as in previous article about CBDB WIFI MAINS power switch  just change the used GPIO Triac opto command pin from outpin=3 to outpin=1 to properly reflect our new MPSM v2 Board setup





For a MAINS Power Dimmer Module, take a look at the new MPDMv3 Module





UPDATE !! UPDATE !! UPDATE !!

As many of you asked for a BOM list, please find it below:

Part Value Device
Package Description






R1 560 R-EU_R1206
R1206 RESISTOR, European symbol
R2 10k R-EU_R1206
R1206 RESISTOR, European symbol
R3 10k R-EU_R1206
R1206 RESISTOR, European symbol
R4 10k R-EU_R1206
R1206 RESISTOR, European symbol
R5 10k R-EU_R1206
R1206 RESISTOR, European symbol
R6 470 R-EU_R1206
R1206 RESISTOR, European symbol
R7 470 R-EU_0207/10
0207/10 RESISTOR, European symbol
R8 390 R-EU_0204/7
0204/7 RESISTOR, European symbol
R9 470 R-EU_R1206
R1206 RESISTOR, European symbol
R10 39/1W R-EU_0309/10
0309/10 RESISTOR, European symbol






C1 100n C-EUC1210
C1210 CAPACITOR, European symbol
C2 100u C-EUC1210
C1210 CAPACITOR, European symbol
C3 0.1u/400V C-EU075-032X103
C075-032X103 CAPACITOR, European symbol






IC1 REG1117 REG1117
SOT223 1A LDO Positive Regulator






LED1
LEDCHIPLED_1206
CHIPLED_1206 LED
LED2
LED3MM
LED3MM LED






OK1 MOC3041M MOC3041M
DIL06 6-Pin DIP ZCD Optoisolator Triac Driver
T1 BT137 BT137-600
TO220BV TRIAC - BT137/600 - NXP






AC_MAINS
MTA02-156
1X2MTA AMP connector
CMD
PINHD-1X2
1X02 PIN HEADER
JP1
PINHD-1X8BIG
1X08-BIG PIN HEADER
JP2
PINHD-1X8BIG
1X08-BIG PIN HEADER
PRG
PINHD-1X2
1X02 PIN HEADER
VIN
PINHD-1X2
1X02 PIN HEADER






ESP12 ESP-12 ESP8266_ESP-12
ESP8266-ESP12
 

 

Tuesday, March 3, 2015

ESP8266 - PIR Motion sensor detection

  First, The Question: What is a PIR sensor?

PIR Sensor with mounted Fresnel Lens

    A PIR module is basically made of a pyroelectric sensor (see it below as the round metal can with a rectangular crystal in the center), which can detect levels of infrared radiation. Everything emits some low level radiation, and the hotter something is, the more radiation is emitted. The sensor in a motion detector is actually split in two halves. The reason for that is that we are looking to detect motion (change) not average IR levels. The two halves are wired up so that they cancel each other out. If one half sees more or less IR radiation than the other, the output will swing high or low. 

PIR Sensor uncovered
    Along with the pyroelectic sensor is a bunch of supporting circuitry, resistors and capacitors. It seems that most small hobbyist sensors use the Micro Power PIR Motion Detector IC BISS0001 . This chip takes the output of the sensor and does some minor processing on it to emit a digital output pulse from the analog sensor.

Bottom Side
Micro Power PIR Motion Detector IC
    In PIR module description you can find that it's powered at 5V!  And as you know already ESP8266 it's a 3V only chip. This thing can be a joy-breaker.  

    The good thing is that if you look in the BISS0001 datasheet you will see that it's working ok also at 3V level. So maybe we are lucky today.

   Looking deeper on the PIR Module board we can find even better news: The board it's actually already a 3V one! The 5V voltage from the power pin is going only to the onboard power regulator! Output is at 3V logic levels. No level shifting or anything else needed ! Neat!

Holtek 3.3V LDO power regulator
     This give us 2 options for powering it up: using the existing 5V pin or if you want to use it in a 3V only setup, just bypass or remove the regulator and that's it.

     Connecting the PIR sensor module is pretty trivial, as it has only 3 PIN: GND, DOUT and VCC. The PIR acts as a digital output so all you need to do is listen for the pin status change to HIGH (motion detected) or LOW (no motion detected).

What we will need:


PIR Motion Detection Software

For programming CBDB Board and uploading the driver and the software we will continue to use the LuaUploader as before.


First test program: Blink a LED when movement detected

PIR "Blinky" running
1. Initialise used PINs:
 
       outpin=3                       -- Select output pin - GPIO0
       gpio.mode(outpin,gpio.OUTPUT)

       inpin=6                        -- Select input pin - GPIO12 
       gpio.mode(inpin,gpio.INT,gpio.PULLUP)  -- attach interrupt to inpin

2. Motion Detection function - called by the trigger on rising edge
      
      function motion()
           print("Motion Detected!")
          gpio.write(outpin,gpio.HIGH)  -- Led ON - Motion detected
          tmr.delay(5000000)           -- delay time for marking the movement
         gpio.write(outpin,gpio.LOW)   -- Led OFF
      end


3. Trigger INPIN on rising edge - based on internal interrupt mechanism 

       gpio.trig(6,"up",motion)


Save the code on ESP as 'pir.lua', restart ESP and run:      
        dofile(pir.lua")  -- Start PIR Program


First Test video: 



If everything looks great we can move to the next part

Example 2: Web enabled PIR Motion detection

  To be able to see online the PIR sensor status we will add a Web Server component to our program

2.1. Web Server 

srv=net.createServer(net.TCP)
  srv:listen(80,
     function(conn)
        conn:on("receive",function(conn,payload) print(payload)
        conn:send("HTTP/1.1 200 OK\n\n")
        conn:send("<META HTTP-EQUIV=\"REFRESH\" CONTENT=\"2\">")
        conn:send("<html><title>PIR Motion Detector Server - ESP8266</title><body>")
        conn:send("<h1>PIR Motion Detector Server - ESP8266</h1><BR>")
        conn:send('Status: ')
            if (stat == "ON") then conn:send('<B><font color=red>Movement Detected!</font></B>')
            elseif (stat == "OFF") then conn:send('<B><font color=green>No Movement</font></B>')
              else                     
                conn:send(stat)
                conn:send('%')
            end
           conn:send("<BR><BR><br>Node.HEAP : <b>" .. node.heap() .. "</b><BR><BR>")
           conn:send("IP ADDR    : <b>".. wifi.sta.getip() .. "</b><BR>")
           conn:send("TMR.NOW    : <b>" .. tmr.now() .. "</b><BR<BR><BR>")
           conn:send("</html></body>")
           conn:on("sent",function(conn) conn:close() end)
      end)
end)


2.2 Motion Detection function.

Splitted in 2 separate functions, to easier understand the mechanism behind:

2.2.1  Trigger on rising edge
  
        function motion()
           print("Motion Detection : ON!")
          stat = "ON"
          gpio.write(outpin,gpio.HIGH)  -- Led ON - Motion detected
         gpio.trig(6,"down",nomotion)  -- trigger on falling edge
        return stat
     end




2.2.2  Trigger on falling edge

     function nomotion()
         print("Motion Detection : OFF!")
         stat = "OFF"
        gpio.write(outpin,gpio.LOW)   -- Led OFF
        gpio.trig(6,"up",motion)  -- trigger on rising edge
       return stat
   end


Save the code on ESP as 'pir.lua', restart ESP and run:      
        dofile(pir.lua")  -- Start PIR Program


Example 2 Video:



Now, if all OK, you can replace the output LED with the Main power switch module.
Take a look on the previous project for connections. After properly connecting it, rerun Example 2. 
You have a fully functional MAINS power switch with motion detection: 




That's all for today, thank you for your great feedback and looking forward for your suggestions!