Showing posts with label USB adapter. Show all posts
Showing posts with label USB adapter. Show all posts

Wednesday, May 3, 2017

ESP8266 USB Programmer USBProg


USBPrg v8.4 -  a fully isolated SAFE USB to Serial adapter for communcation and programming devices protecting your USB ports and devices.


The perfect companion for a complete Development platform for your projects!

Now available on TINDIE Store: https://www.tindie.com/products/nEXT_EVO1/usbprgv84-isolated-usb-serial-programmer-adapter/

You can buy it a special price in the MPRSx8 Home Automation Development pack - MPRSx8 Dev Board + USPPrgv8.4  programmer: https://www.tindie.com/products/nEXT_EVO1/wifi-8x-mains-relays-board-for-home-automation/


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

What is it?

 

  A fully isolated USB to Serial adapter for communication and also programming devices protecting your USB ports and connected devices.
  Integrated hardware Autoreset function makes it suitable for direct programming ESP8266, ESP32 and other MCU's that require it.
  If you use Arduino IDE/Platformio/etc for example with ESP8266, you will love it, as it doesn't need to press anymore RST/Prog buttons for new sketch upload! The autoreset function takes care of that, putting automatically the ESP8266 module in the right boot mode.


Youtube Video step-by-step Tutorial on how to use it to program a ESP8266 Module:



 In the case above ESP8266 is embedded on a MPRSx8 Home Automation board but in the same easy way can be used for programming standalone ESP8266 modules.


Pinout



      Capabilities

    • Fully isolated interface
    • High speed (can work OK also at 115200 and up - used it with Arduino IDE/Platfromio at 921600)
    • DTR/RTS/autoreset function
    • 2.5 kV RMS integrated digital isolator from Silicon Labs
    • High electromagnetic immunity
    • Ultra low power
    • Schmitt trigger inputs
    • Transient Immunity 50 kV/μs

     

    Schematics

    USB interface



    Digital isolator



    Auto-reset circuit


    Below you can find also the wiring for the MPRSx8 Home Automation Board Programming:







    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 24, 2015

    ESP8266 Ultimate DevBoard - Finally Arrived!!




       What do you really expect from a IOT Development board?

       I'm sure most of you will say easy configurable Internet access. Direct Wifi if possible.

       And after that?

       What do you think do you need mostly for your IOT Projects?

       Maybe some sort of easy interaction and data exchange with the real world environment?


      Sounds intriguing to start with so many questions but they are more than legitimate:

      When removing all the bells and whistles, what do we REALLY need to develop the next level of IOT devices?


        If you asked yourself already all these questions, and I'm sure a lot of you has done it already, thinking on your own future projects, what do you think about a IOT Development Board that can offer you at least:



       Sounds good? sounds impossible? Well...I hope that I have, at least for a part of you, one of the right answers below:

    CBDB v2 Schematic


      A DevBoard full of functions in a 5x5 size PCB, small enough to easy integrate in your hobbyist workplace ecosystem :)


    CBDB V2 DevBoard PCB - TOP


       Latest design review PCBs of the fresh new ESP8266 Dev Board v.2 just landed on my desk and is definitely a next step in Experimenting in the IOT world. Designed with ease of use and flexibility in mind it will offer you endless hours of Experimenting, Programming and Developing your own projects.



         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:
      http://dirtypcbs.com/view.php?share=5876&accesskey=3d0fd70d53d6dc20c0bf0255f67cde65

         Please keep in mind this is a experimental board, not a commercial product and is offered as it is. If it will burn your house, help the Aliens to abduct you or even eat your cat it's your problem not mine. The old enough ones to remember ALF will understand even deeper the disclaimer :)


      On the TOP side, you can easily directly integrate your LCD or if you want it separate just run it thru a usual cable:
     
    CBDB v2 - TOP


         After finished soldering, cleaning and cooling down, this is how is looking the ESP8266 CBDBv2 DevBoard ready for testing  the onboard regulator :



    Testing was done with power supplied from a Li-Ion Battery pack and also from a standard 5V SMPS unit under a decent 500mA load. No overheating or nasty oscillations, looks good up to 800mA. Are 800mA warm but the proper calculated double side heatsink area is doing the job right :).


    Onboard regulator test - 5V  SMPS Supply


        I know it's a big debate this days about 1A requirement for ESP8266 Modules, but from all my experience and informations, at least with the ESP-07/12 Modules I had in my hands in the latest months, they were never exceed the 250mA margin. In fact, I have one module running for months now as a temperature logger/webserver and the power consumption looks constantly as in the pictures below:

    Full drain test with thinkspeak data upload and 1/s direct web access reload



    Temperature  Logger supply line monitoring


       I must also admit that I have also some old ESP-01 Modules, never used them, they are indeed looking very power hungry but never had the time to check them how much power they require to properly operate. Or if they are just faulty.

       I have seen before entire batches of faulty ESP8266 modules. Even ESP-07 ones if you remember the story. What I can confirm about these ESP-01 modules is that they cannot be programmed using power directly from my CP2102 USB Adapter, as ESP-07/12. Not enough juice for them. Why? If I will find some time will take a look at them. If is anybody out there that has the answer, please share it with us.


    And finally, this is how is looking, ready for firmware upload and first tests:
     ESP8266 DevBoard

    Stay tuned for what will follow soon:  firmware uploading and the infamous Blinky test:)



    Thursday, April 9, 2015

    Mailbag Arrival !! DS3231 - I2C Real Time Clock Module





         If  you remember my article about PCF8563 Real Time Clock  this one was a looong avaited MailBox hit. Actually I didn't expect it to show anymore after so much time but miracles happening sometime :)

         The DS3231 is a extremely accurate I2C real-time clock (RTC) with an integrated temperature-compensated crystal oscillator (TCXO) and crystal.

         The device incorporates a battery input, and maintains accurate timekeeping when main power to the device is interrupted. The integration of the crystal resonator enhances the long-term accuracy of the device as well as reduces the piece-part count in a manufacturing line.

         The RTC maintains seconds, minutes, hours, day, date,month, and year information. The date at the end of the month is automatically adjusted for months with fewer than 31 days, including corrections for leap year. The clock operates in either the 24-hour or 12-hour format with an AM/PM indicator. 


          Two programmable time-of-day alarms and a programmable square-wave output are provided. Address and data are transferred serially through an I2C bidirectional bus.
     

          A precision temperature-compensated voltage reference and comparator circuit monitors the status of VCC to detect power failures, to provide a reset output, and to automatically switch to the backup supply when necessary. Additionally, the RST pin is monitored as a pushbutton input for generating a μP reset.

     
    DS3231 Typical Operating Circuit


    FEATURES :
    •  Highly Accurate RTC Completely Manages All Timekeeping Functions
                •   Real-Time Clock Counts Seconds, Minutes, Hours, Date of the Month, Month, Day of 
                       the   Week, and Year, with Leap-Year Compensation Valid Up to 2100
                •  Accuracy ±2ppm from 0°C to +40°C
                •  Accuracy ±3.5ppm from -40°C to +85°C
                •  Digital Temp Sensor Output: ±3°C Accuracy
                •  Register for Aging Trim
                •  Active-Low RST Output/Pushbutton Reset Debounce Input
                •  Two Time-of-Day Alarms
                •  Programmable Square-Wave Output Signal

    • Simple Serial Interface Connects to Most Microcontrollers
                •  Fast (400kHz) I2C Interface
    • Battery-Backup Input for Continuous Timekeeping
                •  Low Power Operation Extends Battery-Backup Run Time
                •  3.3V Operation

    • Operating Temperature Ranges: Commercial (0°C to +70°C) and Industrial (-40°C to +85°C)
    • Underwriters Laboratories® (UL) Recognized
       
     For more details, please see  DS3231 Datasheet



    DS3231 Module:

     
    Top


    Bottom

    Close-up

        As you can see from the pictures above, a nice compact module, with backup battery holder on the back (CR2032). Also you can find on the same module sharing the I2C bus a 24C32N EEPROM ( 32k - 4096 x 8) , totally independent from the RTC circuit. A nice addon for a possible WIFI Datalogger system, what do you think about? :)

      32k might sound a small amount of data storage but depending on your application requests might be more than enough for collecting 6 moths or a year data, even more. As I know already from your requests that this subject is of big interest, we will elaborate more about this one in the next article, for now let's go back to our fancy RTC :)


    Clock and Calendar - Theory of operation

       The time and calendar information is obtained by reading the appropriate register bytes. The time and calendar data are set or initialized by writing the appropriate register bytes. The contents of the time and calendar registers are in the binary-coded decimal (BCD) format.
     

        The DS3231 can be run in either 12-hour or 24-hour mode. Bit 6 of the hours register is defined as the 12- or 24-hour mode select bit. When high, the 12-hour mode is selected. In the 12-hour mode, bit 5 is the AM/PM bit with logic-high being PM. In the 24-hour mode, bit 5 is the 20-hour bit (20–23 hours).
     

    The century bit (bit 7 of the month register) is toggled when the years register overflows from 99 to 00.
     

       The day-of-week register increments at midnight. Values that correspond to the day of week are user-defined but must be sequential (i.e., if 1 equals Sunday, then 2 equals Monday, and so on). Illogical time and date entries result in undefined operation.
     

       When reading or writing the time and date registers, secondary (user) buffers are used to prevent errors when the internal registers update. When reading the time and date registers, the user buffers are synchronized to the internal registers on any START and when the register pointer rolls over to zero. The time information is read from these secondary registers, while the clock continues to run. This eliminates the need to reread the registers in case the main registers update during a read.
     

       The countdown chain is reset whenever the seconds register is written. Write transfers occur on the acknowledge from the DS3231. Once the countdown chain is reset, to avoid rollover issues the remaining time and date registers must be written within 1 second.

       The 1Hz square-wave output, if enabled, transitions high 500ms after the seconds data transfer, provided the oscillator is already running. 



       What we will need:
    • CBDB Board
    • USB adapter (take a look on Part 1 for details how to connect them together)
    • DS3231 Module from above

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



    Driver implementation

        As DS3231 has a I2C compatible compatible interface, driver building it following more or less the same  process  as before for I2C devices.



    1. Data conversion functions:

      1.1 Decimal to BCD:

            function decToBcd(val)
                 local d = string.format("%d",tonumber(val / 10))
                 local d1 = tonumber(d*10)
                 local d2 = val - d1
                return tonumber(d*16+d2)
             end

      

    1.2  BCD to Decimal:

          function bcdToDec(val)
               local hl=bit.rshift(val, 4)
               local hh=bit.band(val,0xf)
              local hr = string.format("%d%d", hl, hh)
              return string.format("%d%d", hl, hh)
         end


     
    2. Init I2C bus/interface:

            address = 0x51, -- A2, A1, A0 = 0
            id = 0


            init = function (self, sda, scl)
                   self.id = 0
                  i2c.setup(self.id, sda, scl, i2c.SLOW)
           end

     

    3. ReadTime function:

          readTime = function (self)
           wkd = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }
           i2c.start(self.id)
           i2c.address(self.id, self.address, i2c.TRANSMITTER)
           i2c.write(self.id, 0x00)
           i2c.stop(self.id)
           i2c.start(self.id)
           i2c.address(self.id, self.address, i2c.RECEIVER)
           c=i2c.read(self.id, 7)
           i2c.stop(self.id)
           return  bcdToDec(string.byte(c,1)),
                   bcdToDec(string.byte(c,2)),
                   bcdToDec(string.byte(c,3)),
                   wkd[tonumber(bcdToDec(string.byte(c,4)))],
                   bcdToDec(string.byte(c,5)),
                   bcdToDec(string.byte(c,6)),
                   bcdToDec(string.byte(c,7))
       end



    4. SetTime function:

       setTime = function (self, second, minute, hour, day, date, month, year)
           i2c.start(self.id)
           i2c.address(self.id, self.address, i2c.TRANSMITTER)
           i2c.write(self.id, 0x00)
           i2c.write(self.id, decToBcd(second))
           i2c.write(self.id, decToBcd(minute))
           i2c.write(self.id, decToBcd(hour))
           i2c.write(self.id, decToBcd(day))
           i2c.write(self.id, decToBcd(date))
           i2c.write(self.id, decToBcd(month))
           i2c.write(self.id, decToBcd(year))
           i2c.stop(self.id)
       end



    For testing,  pack it together and save the code on ESP as 'ds3231.lua', restart ESP and run:

    -- Set Initial Time and Date
    require('ds3231')                                -- call for new created DS3231 Module Driver
    sda, scl = 2, 1                                      --  declare your I2C interface PIN's
    ds3231:init(sda, scl)                           -- initialize I2C Bus
     ds3231:setTime(5,08,12,3,6,04,15)   -- setTime(s,min,hour,weekday,day,month, year)
    -- get Time and Date
    require('ds3231')
    sda, scl = 2, 1
    ds3231:init(sda, scl)

    s, m, h, d, dt, mn, y = ds3231:readTime()
    =string.format("%s - %s/%s/20%s",d, dt, mn, y)
    =string.format(" %s:%s:%s", h, m, s)


     
    First run test



     5.  Read Time & Date - Print on LCD


       require('st7032i')
       sda, scl = 2, 1
       st7032i:init_i2c(sda, scl)
       st7032i:init_LCD()

       Time_LCD = function()
           s, m, h, d, dt, mn, y = ds3231:readTime()
           date = string.format("%s",dt).."/"..string.format("%s",mn).."/"..string.format("20%s",y)
           st7032i:lcd_print(3,1,date)
           time = string.format("%s",h)..":"..string.format("%s",m)..":"..string.format("%s",s)
           st7032i:lcd_print(4,2,time)
       end

       tmr.alarm(0, 1000, 1, function() Time_LCD() end)  -- set call Time_LCD function Timer





    Monday, April 6, 2015

    18 Bit ADC - MCP3421 - I2C Driver - ESP8266 CBDB



    ----------------------------------  UPDATE  --------------------------------------

    For a ADC Input Frontend with Auto-range capabilities in the 0-40V Input range take a look also at the new ADC Input related article

    ---------------------------------  UPADTE  ----------------------------------------


        After testing the ESP8266 Internal ADC I think it's time to see also a higher resolution ADC at work. For this project we will use Microchip MCP3421 I2C ADC.

       The MCP3421 is a single channel, low-noise, high accuracy delta-sigma A/D converter with differential inputs and up to 18 bits of resolution in a small SOT-23-6 package. The on-board precision 2.048V reference voltage enables an input range of ±2.048V differentially. 
       The device uses a two-wire I2C compatible serial interface and operates from a single power supply ranging from 2.7V to 5.5V.  

        This device has an onboard programmable gain amplifier (PGA). User can select the PGA gain of x1, x2, x4, or x8 before the analog-to-digital conversion takes place.  This allows the MCP3421 device to convert a smaller input signal with high resolution. 

        The device has two possible to configure conversion modes:
    • Continuous mode
    • One-Shot mode. 
        In One-Shot mode, the device enters a low current standby mode automatically after one conversion. This reduces current consumption greatly during idle periods. Very goob for low power battery powered applications.

    FEATURES: 
      • 18-bit resolution
      • Small 6-lead SOT-23 packaging
      • Differential input operation
      • On-board voltage reference with 5 ppm/°C drift
      • On-board PGA, gains of 1, 2, 4, 8
      • Programmable data rate options
        • 3.75 SPS (18 bits)
        • 15 SPS (16 bits)
        • 60 SPS (14 bits)
        • 240 SPS (12 bits)
      • INL 10 ppm of FSR max
      • Low current consumption, 145 µA at 3V
      • One-shot or continuous conversion options
      • Supports I2C™ serial interface
      • Extended temperature range: -40°C to +125°C

        For more details, please see MCP3421 Datasheet


        As been available in SOT-23-6 package, we will use again an DIP adaptor that will make it easy to integrate it on our CBDB Board expansion slots:

    MCP3421 - SOT-23-6 To DIP Adapter

       Our CBDB Board has started to evolve and develop nice, with some interesting functions on board:



        Because of the high interest and the number of requests raised by the CBDB project in the next weeks we will run small batches of CBDB based devboard PCBs. The main purpose of the CBDB board was for local training and drivers development but  if any new one interested please express your wishes at: tech at esp8266-projects.com.

        It will be nothing fancy, just CBDB Board + some extra goodies on a standard 2 side factory made PCB that can help you to connect in minutes a new module and start programming. A nice I2C Dev Board, KISS concept at its plenitude :). 
    A related Article will follow as soon as the first ones will hit the MailBox.

     
    CBDB DevBoard v2.0b

     

        What we will need for our ADC project:
     

    MCP3421 ADC I2C Driver implementation


        As MCP3421 has a I2C compatible compatible interface, driver building it following more or less the same  process  as before for I2C devices.
     
       Few important consideration about MCP3421: 

       The MCP3421 has an 8-bit wide configuration register to select for: PGA gain, conversion rate, and conversion mode. This register allows the user to change the operating condition of the device and check the status of the device operation. The user can rewrite the configuration byte any time during the device operation.

        The MCP3421 device accepts a fully differential analog input signal which is connected on the VIN+ and VINinput pins. The differential voltage that is converted is defined by VIN = (VIN+ - VIN-) where VIN+ is the voltage applied at the VIN+ pin and VIN- is the voltage applied at the VIN- pin. 
        The input signal level is amplified by the programmable gain amplifier (PGA) before the conversion.

        The digital output code produced by the MCP3421 is a function of PGA gain, input signal, and internal reference voltage. In a fixed setting, the digital output code is proportional to the voltage difference between the two analog inputs.
     

       The output data format is a binary two’s complement.
     

       With this code scheme, the MSB can be considered a sign indicator. When the MSB is a logic ‘0’, it indicates a positive value. When the MSB is a logic ‘1’, it
    indicates a negative value. The following is an example of the output code: 
     
    •  for a negative full-scale input voltage: 100...000 
    • for a zero differential input voltage: 000...000
    • for a positive full-scale input voltage: 011...111.

       The MSB is always transmitted first through the serial port. The number of data bits for each conversion is 18, 16, 14, or 12 bits depending on the conversion mode selection.

       LSB size vs. conversion mode set :

       Bit Resolutions     LSB (V)
                     12 bits     1 mV
                     14 bits     250 μV
                     16 bits     62.5 μV
                     18 bits     15.625 μV



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

      1. Init I2C bus/interface

              init = function (self, sda, scl)
                    i2c.setup(0x0, sda, scl, i2c.SLOW)
              end



       2. Write ADC Register Function

             write_ADC_config = function ( self, dev_addr, set) 
                   i2c.start(0x0)
                   i2c.address(0x0, dev_addr ,i2c.TRANSMITTER)
                   i2c.write(0x0,set)
                   i2c.stop(0x0)
              end


      3. READ ADC Function - 12, 14, or 16 bit-mode, 0-2.048V Range


             read_ADC_data = function (self,dev_addr)
                  i2c.start(0x0)
                  i2c.address(0x0, dev_addr,i2c.RECEIVER)
                  c = i2c.read(0x0,3)
                  i2c.stop(0x0)
                  vadc = (bit.lshift(string.byte(c, 1), 8) + string.byte(c, 2))
                  return vadc
              end


    For testing,  pack it together and save the code on ESP as 'mcp3421.lua', restart ESP and run:

            require('mcp3421')                                         -- call for new created MCP3421 Module Driver
            sda=2 --GPIO4
            scl=1 --GPIO5
            mcp3421:init(sda, scl)                                    -- init I2C
            mcp3421:write_ADC_config(0x68, 0x10)     -- Write Register config: 12Bit/CCV/PGA = 1V/V
            adc_val = mcp3421:read_ADC_data(0x68) -- Read ADC Data

            print("ADC Value : "..adc_val)

            lsb=1         -- 12 bit -> LSB = 1mA

            vts = (adc_val * l1)/1000*4.3043     --calibrate based on your power supply, Vref and divider


            print("\nValue = " ..adc_val.." \nVolts = "..string.format("%g",vts).." mV")
            print("\nValue = " ..adc_val.." \nVolts = "..string.format("%.4f",vts).." mV")
     

    MCP3421 ADC - First test
    First Test Video - Noisy environment - Live Bus voltage:

    Filtered clean source voltage measurement :



     4. Read ADC and Print values on LCD 

           read_ADC_LCD1 = function()
                adc_val = mcp3421:read_ADC_data(0x68)
                l1=1         -- 12 bit
                --l1=0.0625    -- 16 bit
               val = (adc_val * l1)/1000*4.3043
               print("    ReadADC     : "..val)
               val = string.format("%g",val)
               st7032i:lcd_print(0,2,adc_val)
               st7032i:lcd_print(9,2,val)
           end


    For testing,  pack it together and save the code on ESP as 'mcp3421.lua', restart ESP and run:

            require('mcp3421')                                         -- call for new created MCP3421 Module Driver
            sda=2 --GPIO4
            scl=1 --GPIO5
            mcp3421:init(sda, scl)                                    -- init I2C
            mcp3421:write_ADC_config(0x68, 0x10)     -- Write Register config: 12Bit/CCV/PGA = 1V/V

            require('st7032i')
            st7032i:init_LCD()


            st7032i:lcd_setCursor(0,1)
            st7032i:lcd_write("ADC_Val  Volts")


           tmr.alarm(0, 1000, 1, function() read_ADC_LCD1() end)  -- read ADC and Print on LCD

    MCP3421 ADC - LCD Print test
    MCP3421 ADC - LCD Print test


            1. Test done in filtered environment - highly stable voltage




            2. Test done in noisy environment - using real bus voltage - unfiltered 




           3. Test done in noisy environment - values are printed directly on CBDB DevBoard LCD Display




                          Thank you all for your continuous support and great feedback!