Showing posts with label Web Switch. Show all posts
Showing posts with label Web Switch. Show all posts

Tuesday, April 12, 2016

MPDMv4 - Universal AC MAINS Dimmer








For any new orders/requests please feel free to use as usual: tech at esp8266-projects.com. 
   
    MPDMv4 Boards are also available on Tindie: AC MAINS Dimmer - MPDMv4


--------------------------------------------------- DISCLAIMER --------------------------------------------------
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.
----------------------------------------------------------------------------------------------------------------------------
 
                                                             Creative Commons License

MPDMv4 by ESP8266-Projects.com is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.  

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


  
And the story behind:



  EVOLUTION.

  The next step in the MAINS Power Dimmer/Switch series.

   One of the main problem that people has been complained about was the fact that a simple MAINS Power Dimmer/Switch unit like the basic one presented last year is using sometime too much resources from a already overloaded application MCU/processor:

MPDMv3 - MAINS Dimmer/Switch with Phase detection


   One of the scenarios, directly related with ESP8266 is about the limited timers capabilities that you have. For example,  if you want to implement a proper web server to directly serve your webpages from ESP8266 you are automatically using one timer. If you want to start using the second one for your ZCD processing ...well...it's becoming very tricky. Very.

   Don't uderstand me wrong, a bigger, better MCU can do it probably very well, but even then if you have the chance to free some resources easily, do it!. And  I really cannot see a ESP8266 acting as a App MCU (webserver, data logger, MQTT client, etc, etc) and doing reliable also other demanding functions as  Processing Zero Crossing Detection.


   SOLUTION? 

    I can see only one, and it is a lesson learned many years ago: keep your real-time processing functions away from your Application MCU/Processor. To do that we just need to move the ZCD processing function from the ESP8266/whatever MCU you want to the MPDM Driver itself:


MPDMv4 - MAINS Phase detection and ZCD processing

   What means that? means that in this new configuration our ESP8266 will be free from any type of real-time ZCD processing that is related with the MAINS Dimming process, you just  need to send to the MPDMv4 driver a voltage (Vcontrol) in a pre-established range (0-3V for example) that will correspond with different desired Dimming levels.

 What we have obtained? A UNIVERSAL MAINS Power Dimmer driver that can be used with any MCU you might want or even no MCU at all. You can dimm it even with a simple Potentiometer at input, no programming, no code, no nothing!!


Legend:  
PURPLE  - Phase detector output
BLUE      - Reversed phase signal (normalised)
Yellow     - Triac Driver CMD signal (PWM)
 

Vcontrol = 0, CMD Duty cycle=6%


Vcontrol = 2V, CMD Duty=50%


Vcontrol = 2.8V,  CMD Duty=96%



  How can be done that? Easy. Use PWM or a DAC, your choice. For ESP8266 I will recommend you to use a DAC, like the MCP4726  or, why not , the MCP4728, for a full 4 Channel MAINS Dimmers solution. PWM in case of the ESP8266..let's say that is has some limitations that you will discover very soon that you don't like :)


The mains advantages of using DAC?

Notable: 

1. Very low to zero overhead on the App MCU
2. High precision (DAC from above are 12 bit!! - 4096 levels of dimming!!)
3. You can use the "set-and-forget" technique using DAC internal nonvolatile memory (EEPROM) and have the same level on the next power-off/on cycle.


  IMPLEMENTATION


   SCHEMATICS

    As the only functional difference between the previous MPDMv3 MAINS Dimmer and the new MPDMv4 is the presence of the ZCD function onboard, basically, without some small bits and pieces around like the MOV protection circuit, you can see it exactly as it is: a MPDMv3 with a ZCD circuit onboard:

MPDMv3 - Phase detection and Triac control


Zero crossing detector circuit




   MPDMv4 PCB:

MPDMv4 PCB

   As you can see from the above picture, it was carefully designed with proper MAINS isolation from the rest of the driver, you can see even the extra isolation slots done for a even bigger Creepage distance.

And because I know this terms still creates some confusion, short definitions below:

CLEARANCE is the shortest distance in air between two conductive parts.
CREEPAGE distance means the shortest distance along the surface of a solid insulating material between two conductive parts.

 A creepage distance cannot be less than the associated clearance so that the shortest creepage distance possible is equal to the required clearance. However, there is no physical relationship, other than this dimensional limitation, between the minimum clearance in air and the minimum acceptable creepage distance.


And the new, freshly baked result:

MPDMv4 - MAINS Power Dimmer/Switch with Phase detection and ZCD Processing


Next time we will move on to the Software side, to see what is going on with our Webserver interface & stuff.



Monday, August 17, 2015

Arduino IDE - WIFI MAINS Power Switch - ESP8266 MPSMv2

--------------------------------------------------------------------------------------------------------------------------
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!
---------------------------------------------------------------------------------------------------------------------------- 
  
   For any new orders / requests please feel free to use as usual: tech at esp8266-projects.com.
 
   If you want for your own experiments to order ESP8266 WIFI Web Power Switch for MAINS - MPSM v.2 DevBoard bare PCBs only, you can also do it directly at Dirty PCBs, our preferred PCB House:


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



   For reference please take a look at the original WIFI MAINS power switch module (MPSMv2) article link:
http://www.esp8266-projects.com/2015/04/p2-wifi-web-power-switch-for-mains-mpsm.html



   As you might remember from the previous related article about MPSMv2 Board the software examples were done in NodeMCU LUA.

  I was asked to make also a short, basic introduction also for Arduino IDE, so here we go. But before of that I need to make also a short presentation of the MPSMv2 Board with few extra explanations. I will not insist too much on the hardware/schematics/theory of operation part of the story as you have all the details already in the previous articles about, including BOM.

  What I want to explain a bit is the concept behind that might help you to understand better how to use the board. To ease the understanding you can see MPSMV2 as 2 separate Boards spliced together,  a Breadboard friendly ESP8266 adapter with integrated 3.3V Power Supply, and a MAINS Triac Switch.

    The PCB is designed in such way that no harm will be done by cutting it in half as in the below picture.
MPSMv2 Board - Full and splitted

  You can use separatelly the 2 parts, the ESP8266 Adapter with 3V3 regulator and the Triac MAINS Power Switch.

MPSMv2 - ESP8266 adapter with voltage regulator & stuff on the back

   The Triac Switch part can be used directly even with a different ARM, PIC, Arduino, whatever MCU you have arround without any problems as long as it has a GPIO pin capable to drive the MOC Optocoupler LED thru CMD port.

Triac Driver part - use proper Fuse and EMI filtering!

   Please keep in mind that de design was done in such a basic way as been designed to be part of a bigger system and used for development and testing.

   Please use propper MAINS protection, FUSE and EMI filtering block based on your specific application requirements!

  There were a lot of questions and debates about, including the Hackaday one, why it has not a FUSE, where is the filtering, etc, etc ... they are not there because should not be there in our MPSMv2 design.
   Input protection/filtering block for MAINS should not be on the same board with the driver. They are a lot of explanations behind this but even only having more flexibility in mind should suffice.
If you look at the EMI filter below, similar with the choosen one as suitable to be used in our project you will understand even more why should be not on the MPSMv2 board.

EMI filter vs. MPSMv2 Board


    Now let's go back to our main story for today: how to use MPSMv2 with Arduino IDE.


What we will need:




1. Software installation

If you didn't have yet installed a proper running ESP8266 Arduino IDE environment the ESP8266 Arduino IDE installation Article might help you. Or the Youtube video from below:







2. Wiring

Connect the MPSMv2 Module to the USB adapter as in the picture below:

MPSMv2 - USB Adapter Wiring

USB         MPSMv2
  Rx      ->    Tx
  Tx      ->     Rx
  GND  ->    GND
  +5V   ->     Power input port +5V

   Set the PRG jumper (Blue) for programming mode ON !



3. Arduino IDE Programming.

  • Start Arduino IDE
  • Select inside IDE your desired ESP8266 Board (default one should be also OK).
  • Plug-in the USB adapter connected with the MPSMv2 module as above, will see the power on LED's 
  • Open in IDE the basic Blink program
  • Replace the  digital pin 13 as an output PIN with1.
  • Compile and upload the program to MPSMv3 board.


 The result:





Let's test also the Triac driver command pin:





Q & A :

  • How can you have more than a MAINS power switch channel available? Very simple: just cut the Triac driver part from other MPSMv2 PCB's and connect the Driver side only to the full size MPSMv2 Board. 
  • How many independent MAINS lines can be driven by a single MPSMv2 Board? As many as free IO pins you have available in your project and Triac Drivers you might add to it.   
  • What's the easiest way to have 2 MAINS lines swiched synchronous? Just connect the CMD port from a second available Triac module to the CMD port on the main MPSMv2 Triac Module. The Triac driver from the MPSMv2 will be commanded in sync with the second connected one.









Monday, June 8, 2015

Mailbag Arrival !! MAX7219 - 8 Digit LED Display Driver



     First RUN test for MAX7219 LED Display Module using ESP8266 CBDBv2 EVO Board




 

    Another very popular and widely available module, used already in many Projects before, meeting the ESP8266 ecosystem :)



    You can buy MAX7219 modules from Banggood, Amazon, Ebay, nameyourfavorite.com, quality and price might hugely vary from one to another so don't choose the cheapest one in town as you might find it as been not a very good deal to the end.


Description

   The MAX7219 are compact, serial input/output common-cathode display drivers that interface microprocessors (µPs) to 7-segment numeric LED displays of up to 8 digits, bar-graph displays, or 64 individual LEDs. Included on-chip are a BCD code-B decoder, multiplex scan circuitry, segment and digit drivers, and an 8x8 static RAM that stores each digit. Only one external resistor is required to set the segment current for all LEDs.

   A convenient 4-wire serial interface connects to all common µPs. Individual digits may be addressed and updated without rewriting the entire display. The MAX7219  also allow the user to select code-B decoding or no-decode for each digit.

   The devices include a 150µA low-power shutdown mode, analog and digital brightness control, a scan-limit register that allows the user to display from 1 to 8 digits, and a test mode that forces all LEDs on.


Key Features

  • 10MHz Serial Interface
  • Individual LED Segment Control
  • Decode/No-Decode Digit Selection
  • 150µA Low-Power Shutdown (Data Retained)
  • Digital and Analog Brightness Control
  • Display Blanked on Power-Up
  • Drive Common-Cathode LED Display
  • 24-Pin DIP and SO Packages


Typical Application Circuit


  This is a 5V operation device. If you need to run it by the book at 3.3V Logic Level you will need to use a level shifter. In practice, as you will see below,  you can try and run it directly, a bit out of spec.   As MAX7219 HIGH logic level is at 3.5V...well...looks like it's working quite OK also in this way, in 48 hours of continuous running no freeze or strange behaviour:)

For more details please see MAX7219 Datasheet

For a true native 3V operation or segment blinking,  take also look to the MAX6951 datasheet.



What we will need:



MAX7219 - CBDBv2 EVO Connection


Wire        MAX7219     ESP8266

Green      +5Vcc
Blue        GND               GND
Yellow     DIN                 13
White      CS                  12
Orange    CLK                14




MAX7219 Driver  Implementation


  Timing Diagram





  Initial Power-Up

  On initial power-up, all control registers are reset, the display is blanked, and the MAX7219 enter shutdown mode.
  Program the display driver prior to display use. Otherwise, it will initially be set to scan one digit, it will not decode data in the data registers, and the intensity register will be set to its minimum value.


  Shutdown Mode

   When the MAX7219 is in shutdown mode, the scan oscillator is halted, all segment current sources are pulled to ground, and all digit drivers are pulled to V+, thereby blanking the display.
  • Data in the digit and control registers remains unaltered.
  • Shutdown can be used to save power or as an alarm to flash the display by successively entering and leaving shutdown mode.
  • For minimum supply current in shutdown mode, logic inputs should be at ground or V+ (CMOS-logic levels).
  • Typically, it takes less than 250μs for the MAX7219 to leave shutdown mode.
A nice thing is the fact that the display driver can be programmed while in shutdown mode, and shutdown mode can be overridden by the display-test function.



  Serial-Addressing Modes

   For the MAX7219, serial data at DIN, sent in 16-bit packets, is shifted into the internal 16-bit shift register with each rising edge of CLK regardless of the state of LOAD. For the MAX7221, CS must be low to clock data in or out. The data is then latched into either the digit or control registers on the rising edge of LOAD/CS.

  LOAD/CS must go high concurrently with or after the 16th rising clock edge, but before the next rising clock edge or data will be lost. Data at DIN is propagated through the shift register and appears at DOUT 16.5 clock cycles later.
Data is clocked out on the falling edge of CLK.
Data bits are labeled D0–D15.
D8–D11 contain the register address.
D0–D7 contain the data, and D12–D15 are “don’t care” bits.
The first received is D15, the most significant bit (MSB).





Digit and Control Registers



14 addressable digit and control registers.
The digit registers are realized with an on-chip, 8x8 dual-port SRAM. They are addressed directly so that individual digits can be updated and retain data as long as V+ typically exceeds 2V.
The control registers consist of decode mode, display intensity, scan limit(number of scanned digits), shutdown, and display test (all LEDs on).



   Decode-Mode Register

   The decode-mode register sets BCD code B (0-9, E, H, L, P, and -) or no-decode operation for each digit.
   Each bit in the register corresponds to one digit.
   A logic high selects code B decoding while logic low bypasses the decoder.



  When the code B decode mode is used, the decoder looks only at the lower nibble of the data in the digit registers (D3–D0), disregarding bits D4–D6. D7, which sets the decimal point (SEG DP), is independent of the decoder and is positive logic (D7 = 1 turns the decimal point on).




When no-decode is selected, data bits D7–D0 correspond to the segment lines of the MAX7219/MAX7221.






Intensity Control and Interdigit Blanking

  The MAX7219 allow display brightness to be controlled with an external resistor (RSET) connected between V+ and ISET.
  The peak current sourced from the segment drivers is nominally 100 times the current entering ISET.
   This resistor can either be fixed or variable to allow brightness adjustment from the front panel.
   Its minimum value should be 9.53kΩ, which typically sets the segment current at 40mA.
   Display brightness can also be controlled digitally by using the intensity register.  
   Digital control of display brightness is provided by an internal pulse-width modulator, which is controlled by the lower nibble of the intensity register.
   The modulator scales the average segment current in 16 steps from a maximum of 31/32 down to 1/32 of the peak current set by RSET.
The minimum interdigit blanking time is set to 1/32 of a cycle.




Scan-Limit Register

The scan-limit register sets how many digits are displayed, from 1 to 8.
They are displayed in a multiplexed manner with a typical display scan rate of 800Hz with 8 digits displayed.
If fewer digits are displayed, the scan rate is 8fOSC/N, where N is the number of digits scanned.
Since the number of scanned digits affects the display brightness, the scan-limit register should not be used to blank portions of the display (such as leading zero suppression).




Display-Test Register

The display-test register operates in two modes: normal and display test. Display-test mode turns all LEDs on by overriding, but not altering, all controls and digit registers(including the shutdown register).



In display-test mode, 8 digits are scanned and the duty cycle is 31/32



Software


1.  Init

-- MAX7219 registers
MAXREG_DECODEMODE = 0x09
MAXREG_INTENSITY  = 0x0a
MAXREG_SCANLIMIT  = 0x0b
MAXREG_SHUTDOWN   = 0x0c
MAXREG_DISPTEST   = 0x0f


DIN   = 7      -- 13 - data in pin
CS    = 6      -- 12 - load (CS) pin
CLK   = 5      -- 14 - clock pin

gpio.mode(DIN,gpio.OUTPUT)
gpio.mode(CS,gpio.OUTPUT)
gpio.mode(CLK,gpio.OUTPUT)



2. Write serialised data

function wrByte(data)
   i=8
   while (i>0) 
   do
       mask = bit.lshift(0x01,i-1)
       --print(mask)
       gpio.write( CLK, 0)    -- tick
       dser = bit.band(data,mask)
       if (dser > 0)
         then gpio.write(DIN, 1)   -- send 1
              --print("1")
         else gpio.write(DIN, 0)   -- send 0
              --print("0")
       end --endif
       --print(dser)
       gpio.write( CLK, 1)    -- tick
       i=i-1
    end --while
end



3. Set Register

function setReg(reg, value)
  gpio.write(CS, 0)

  wrByte(reg)   -- specify register
  tmr.delay(10)
  wrByte(value) -- send data

  gpio.write(CS, 0)
  --tmr.delay(10)
  gpio.write(CS, 1)
end



4. Convert anf Print integer number in xxxx format

 function print_led_int(c)
   th = string.format("%d",c / 1000)
   h = string.format("%d",(c-th*1000) / 100)
   t = string.format("%d", (c-th*1000-h*100) / 10)
   u = string.format("%d", c-th*1000-h*100-t*10)
   --print(string.format("%d %d %d %d", th,h,t,u))
   setReg(4, th)
   setReg(3, h)
   setReg(2, t)
   setReg(1, u)
end



5. Create a  Display 'ZERO' init stage

function zero_all()
   v=1
   while (v<9) do
       setReg(v,0)
    v=v+1
   end
end



6.  MAX7219 Initialisation  

setReg(MAXREG_SCANLIMIT, 0x07)
tmr.delay(100)
setReg(MAXREG_DECODEMODE, 0xFF)    -- full decode mode BCD
tmr.delay(100)
setReg(MAXREG_SHUTDOWN, 0x01)          -- not in shutdown mode
tmr.delay(100)
setReg(MAXREG_DISPTEST, 0x00)              -- no display test
tmr.delay(100)
setReg(MAXREG_INTENSITY, 0x00)            -- set Brightness
zero_all()                                                        -- set all to ZERO



7. Test Display - 9999 counter

count=0
tmr.alarm(0,1000,1,
   function() 
       count=count+1;
       --print(count);
       print_led_int(count)
       if (count>9999) then count=0;zero_all()
       end
   end)




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:





Monday, May 4, 2015

P3 - WIFI Mains Power Dimmer / Switch with CBDBv2



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!

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

   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:

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

    For that ones of you that have already read my articles related with MAINS Power Switching
 you remember that the above modules were ON/OFF switching only.

    Now it's about time to talk also about what many of you has asked for: DIMMING!
   It's a total different story, liitle bit complicated but, as you will see, not so hard to understand.

 
General considerations

    There are several types of dimmers generally available. These are used for resistive, and inductive loads, such as incandescent,cold cathode and low voltage (inductive) lamp sources. Note that not all electronic transformers used for low voltage lamps are suitable for dimming by Triac or Thyristors dimmers. In case of Thyristors you need 2 of them as Thyristor is a Unidirectional device and because AC power flows in both directions! 
    
   Why using Thyristors? One of the reasons is that they are available in higher power ratings than Triacs and are more robust. A 4-500 A to 1kA ratings is something common for Thyristors. 
Usually you will find this kind of Thyristors in Industrial applications, not exacty a hobbist part.  
 Just look, for example,  at the specifications of ABB 5STP27H2801  and you will understand why :)

  I don't remember a highly available Triac rated more than 40A. BTA40-700B is a good example.




 
  For resistive loads ON-OFF only jobs (no dimming required) a winning combination is between  MOC304X for  Triac driver (Zero voltage crossing one) and a good quality Triac, decently sized at the power needs. 

   In case of dimming you DON'T want to use a zero crossing voltage one! And this is because of the way the dimming process is going and depending on our own ZCD (zero cross detection) function. In our case zero cross detection is done by the biphase optocoupler as in the schematic below


Zero Cross Detection output example


    Mains power is comprised of an alternating current that flows in one direction and then in the other, along the cable, at the rate of 50 or 60 cycles per second.

   The number of cycles in one second is called the frequency.  The frequency is given in a unit called hertz (symbol Hz) where 1 Hz = 1 cycle per second . 

   The value 50 or 60Hz is dependent on the countries power system. The current alternates back and forth changing direction at the zero point.

    If we will to look at the waveform (yellow) with the Osciloscope it would appear as a sinusoidal shape. Drawing a line through the middle and this is what is called the zero crossing point. At this instant in time no current is flowing in either direction.


MAINS 50Hz and ZCD waveforms



   The Triac is electronically synchronized with the help of the ZCD to turn the power ON or OFF. By chopping the waveform at the zero-crossing point, smooth dimming can be achieved without the lamp flickering. This turning on and off of the power device occurs every time the mains crossing point is reached (half phase), 100 or 120 times per second (50 or 60Hz).

Firing Triac at 50%

   ZCD determines the point in time (Firing delay time) at which they turn ON (conduct). The ON state continues until the next zero-crossing point, at which point the Triac turns itself OFF. The command circuit then provides a delay, which equates to the dimness of the lamp, before turning the control device back on. The slight capacitance of the load, filters the chopped waveform resulting in a smooth light output.


NOTE: If you notice that the 50Hz AC Voltage repesented up (yellow) is not around 240VAC and is nor pure sinusoide as should be, it's a simple explanation: I didn't want to put Osciloscope directly on MAINS. For very simple reasons. But this is not affecting at all the general view of the process.






What we will need:
  • CBDB Board or any other ESP/Arduino /MSP/ARM/Whaterver Board you may like
  • USB adapter (take a look on Part 1 for details about the USB Adapter)
  • Main Power Dimmer/Switch module (MPDMv3 - details below)



Main Power Dimmer/Switch module (MPDMv3)


 
     This time the MAINS Dimmer switch module was designed as a standalone unit, not including the ESP8266 anymore, as people were asking for a more general usage one that can be used with existing Setup/Environments. 

    Because the MPSMv2 was designed more as a DevBoard for MAINS switching application and the FUSE and MAINS input / output /filtering unit was keept separatelly  has created some confusion and a lot of talks about, Hackaday thread included :).

    So, this time, you have on the same board, fuse and connectors to directly connect de MPDMv3 module to MAINS, Lightbulb/Lamp and your MCU Board. 


MPDMv3 - Schematic



MPDMv3 - MAINS Dimmer/Switch Module

   Both signals, phase detect (PHS) for ZCD and Triac command (CMD) are fully optocoupled and you have a proper galvanic separation between the low side and the MAINS side voltage, but,  as a general practice DO NOT TOUCH any part of the circuit as long as MAINS power it's applied!! The scope of LED1 is just to help you in the testing phase process, it does not have any other sense on dimming.

Proper clearance and creepage distance were also taken in consideration when PCB was designed:

MPDMv3 - PCB - Bottom side



MPDMv3 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


   As you have seen above on the Osciloscope, zero crossing is the moment when the sinusoide goes through zero. After each zero crossing there is one full half of the sinuswave available to send through the Triac to the Load.

   So what the software needs to do is to detect the zerocrossing, and then wait for a set amount of time on that sinuswave to switch on the TRIAC.


We have a 50Hz VAC that means is 50 waves per second.
Each sinuswave thus takes 1000ms/50=20ms
They are 2 sinus peaks in a wave.  That means that after every zero crossing detection there is a 10ms period that we can regulate.
If we switch Triac directly at the beginning of that period, the load will receive full power
If we do it at the end of that 10ms period the load will receive none and if we do it halfway, the load will receive half power.



Now, how can we obtain the desired number of dimming steps?

If you look at the above explanation you know already the answer: we will divide the 10ms to the number of the steps we want and that's it. The obtained value can be tweaked a bit, depending on how is really looking your AC MAINS and how clean it is, filtering, delays, etc, but that's the dimming steps value you need to start with.

Let's assume we have:
Dimming steps = 128
Waveform Time= 10 ms
Step = 10000/128 = 78

Total dim time then is calculated as desired dimming steps * step value.

Also what we need to take in consideration after we fire the Triac is the Triac ON Propagation time (the time Triac needs to become fully ON).


      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. Fading function for testing mode


     function fading()
         if(dim_up==1) then dim=dim+1
              else dim=dim-1
         end
         if(dim < 10) then dim_up=1 dim=10
              else if (dim > 120 ) then dim_up=0 dim=120
         end
         end 
         print("Dimmer level : " .. dim)
         print("Fading mode  : " .. dim_up)
         tmr.wdclr()
    end





4. Main code

       dim = 120                                                          -- Dimmer level - smaller value is brighter
       dim_up=0                                                          -- Fading direction - for test  run

       gpio.trig(inpin,"up",zero_cross)                       -- ZCD interrupt attached - trigger on falling edge
       tmr.alarm(0, 100, 1, function() fading() end)     --timer for testing mode



For testing, just save the code on ESP as 'dimmer.lua', restart ESP and run:   
            dofile("
dimmer.lua")  -- Start the Dimmer Testing  mode

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("dimmer.lua")  -- Start the Dimmer Testing mode

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




Testing Zero Cross Detector




First test - Dimming a Lamp





UPDATE!! UPDATE !! UPDATE !!

As requested, please find below MPDMv3 BOM:

No Part Value Package Description
1 R1 470 R1206 RESISTOR, European symbol
2 R2 360/1W 0204/7 RESISTOR, European symbol
3 R3 470/1W 0204/7 RESISTOR, European symbol
4 R4 470 R1206 RESISTOR, European symbol
5 R5 39/1W 0207/5V RESISTOR, European symbol
6 R6 47k/1W 0207/10 RESISTOR, European symbol
7 R7 47k/1W 0207/10 RESISTOR, European symbol
8 R8 10k R1206 RESISTOR, European symbol
9 C1 0.01uF/400 X2 C075-032X103 CAPACITOR, European symbol
10 C2 0.05uF/400V C075-032X103 CAPACITOR, European symbol
11 IC1 MOC3021 DIL06B 6-Pin DIP Optoisolators Triac Driver Output
12 IC2 SFH620A DIL04 Optocoupler, Phototransistor Output, AC Input
13 T1 BT137 TO220BV TRIAC
14 PLD CHIPLED_1206 LED
15 PWR_IN DG3XX-02-5.0 DG306-5.0-02P DG350-3.5-02P
16 SW_OUT DG3XX-02-5.0 DG306-5.0-02P DG350-3.5-02P
17 FUSE 5A SHK20Q Fuse
18 U$3 1X4 1X4 2mm Header or 2mm socket


That's all for today, next time we will talk about WEB Interface implementation for our MAINS Power Dimmer / Switch Module!