Sketch for Lightning Sensor


  • Hero Member

    Hi all,

    Has anyone developed a MySensors sketch for the AS3935 Digital Lightning Sensor that's listed in the MySensors store? Playingwithfusion, the manufacturer of the sensor, has a sample sketch, but being new to MySensors, I need some help setting this up to send data to the MS gateway. Thanks in advance for any help.

    Cheers
    Al


  • Contest Winner

    @Sparkman said:

    Playingwithfusion

    cool sensor. Were you able to get it working with your arduino already?

    It looks like you have a few options, but you could try first getting it to work with SoftSPI.h library, and moving the MOSI, MISO and SCLK pins off of the MySensors Hardware SPI pins. Alternatively, you could try to implement using I2C, but I didn't see an example (maybe the manufacturer can provide that).

    Once you have it working with SoftSPI or I2C, it would be easy to help you get it to work with your MySensors Gateway.

    We can help you with the program, but testing would be yours to do, so try to get it working as above, and post that code.


  • Hero Member

    cool sensor. Were you able to get it working with your arduino already?

    Thanks for the response. I haven't hooked it up yet, hopefully tomorrow although not a lot of lightning this time of year where I live to test with. Is it possible to use "normal" SPI and just use a different pin for slave select for it? I was thinking about using pins 8 and 7 for the lightning sensor as to not conflict with the radio on pins 10 and 9, and using pin 3 for IRQ for the sensor versus 2 for the radio. Can both be connected to MOSI, MISO and SCLK? I was looking to use it with a Pro Mini and would need the following SPI parameters:

    SPI.begin();
    SPI.setClockDivider(SPI_CLOCK_DIV8);
    SPI.setDataMode(SPI_MODE1);
    SPI.setBitOrder(MSBFIRST);

    Do these conflict with what's needed for the radio? I guess using I2C would eliminate the conflicts, and will ask Playingwithfusion the details on how to make it work with that. I would like to learn how to get multiple devices playing together using SPI though. I'll read up on SoftSPI as well.

    Cheers
    Al


  • Contest Winner

    presently, MySensors (and @hek can correct me if I am wrong) is still not using interrupt on pin2, so you should be OK there.

    SPI is a hardware implementation on pins 11, 12, 13 on your Arduino. MySensors is using hardware SPI to communicate with the radio.

    SoftSpi is a software implementation of SPI and will allow you to make SPI communication to your breakout board, but must use alternate pins on your Arduino as avoid the conflict.

    You should be able to get it to work with SoftSPI or I2C.


  • Hero Member

    Thanks, but isn't SPI designed to allow more than one slave to be connected? From what I understand, each slave requires a separate slave select pin, but should be able to share the other pins. I'm new to this so please correct me if I'm wrong.

    Thanks
    Al


  • Contest Winner

    @Sparkman said:

    Thanks, but isn't SPI designed to allow more than one slave to be connected?

    yes, if they play well together... I've not been that lucky with Arduino. Since the breakout isn't on a shield, it may work OK.

    You can always just try it and let us know.


  • Hero Member

    @BulldogLowell said:

    yes, if they play well together... I've not been that lucky with Arduino. Since the breakout isn't on a shield, it may work OK.

    You can always just try it and let us know.

    Thanks, I did not realize that. The manufacturer got back to me already (great support over a weekend) and indicated that they don't have a sample I2C sketch, so I'll likely try getting it working with SPI first.

    Cheers
    Al



  • @BulldogLowell @Sparkman
    Hi guys, Have any of you made any developments? I was wondering, can I make changes to distance sensor sketch and use it for lighting?

    as3935_lightning_snsr_nocal.ino
    PWFusion_AS3935.cpp
    PWFusion_AS3935.h


  • Hero Member

    @jeylites I haven't done much with it as I was waiting for my NRF24l01's to show up, First shipment got lost and my replacement shipment seems to be stuck in customs for far too long. I'm hoping to get back to it in a couple of weeks. I did write a sketch that compiled and loaded properly, but I haven't been able to test it due to lack of radios ๐Ÿ˜ž

    Cheers
    Al



  • @Sparkman OK, hope to hear from you soon. Cheers!


  • Hero Member

    My radios showed up a few days ago and this is the sketch I'm using:

    #include "MySensor.h"  
    
    // the sensor communicates via SPI or I2C. This example uses the SPI interface
    #include "SPI.h"
    // include Playing With Fusion AXS3935 libraries
    #include "PWFusion_AS3935.h"
    
    // setup CS pins used for the connection with the sensor
    // other connections are controlled by the SPI library)
    int8_t CS_PIN  = 8;
    int8_t SI_PIN  = 7;
    int8_t IRQ_PIN = 3;                      
    volatile int8_t AS3935_ISR_Trig = 0;
    
    // #defines
    #define AS3935_INDOORS       1
    #define AS3935_OUTDOORS      0
    #define AS3935_DIST_DIS      0
    #define AS3935_DIST_EN       1
    #define AS3935_CAPACITANCE   96      // <-- SET THIS VALUE TO THE NUMBER LISTED ON YOUR BOARD 
    // prototypes
    void AS3935_ISR();
    
    PWF_AS3935  lightning0(CS_PIN, IRQ_PIN, SI_PIN);
    
    #define CHILD_ID_DISTANCE 1
    #define CHILD_ID_INTENSITY 2
    MySensor gw;
    MyMessage msgDist(CHILD_ID_DISTANCE, V_DISTANCE);
    MyMessage msgInt(CHILD_ID_INTENSITY, V_VAR1);
    
    void setup()  
    { 
      gw.begin();
    
      // Send the sketch version information to the gateway and Controller
      gw.sendSketchInfo("Lightning Sensor", "1.0");
    
      // Register all sensors to gw (they will be created as child devices)
      gw.present(CHILD_ID_DISTANCE, S_DISTANCE);
      gw.present(CHILD_ID_INTENSITY, S_CUSTOM);
      boolean metric = gw.getConfig().isMetric;
    
      Serial.begin(115200);
      Serial.println("Playing With Fusion: AS3935 Lightning Sensor, SEN-39001");
      Serial.println("beginning boot procedure....");
      
      // setup for the the SPI library:
      SPI.begin();                            // begin SPI
      SPI.setClockDivider(SPI_CLOCK_DIV4);    // SPI speed to SPI_CLOCK_DIV16/1MHz (max 2MHz, NEVER 500kHz!)
      SPI.setDataMode(SPI_MODE1);             // MAX31855 is a Mode 1 device
                                              //    --> clock starts low, read on rising edge
      SPI.setBitOrder(MSBFIRST);              // data sent to chip MSb first 
      
      lightning0.AS3935_DefInit();                        // set registers to default  
      // now update sensor cal for your application and power up chip
      lightning0.AS3935_ManualCal(AS3935_CAPACITANCE, AS3935_OUTDOORS, AS3935_DIST_EN);
                      // AS3935_ManualCal Parameters:
                      //   --> capacitance, in pF (marked on package)
                      //   --> indoors/outdoors (AS3935_INDOORS:0 / AS3935_OUTDOORS:1)
                      //   --> disturbers (AS3935_DIST_EN:1 / AS3935_DIST_DIS:2)
                      // function also powers up the chip
                      
      // enable interrupt (hook IRQ pin to Arduino Uno/Mega interrupt input: 0 -> pin 2, 1 -> pin 3 )
      attachInterrupt(1, AS3935_ISR, RISING);
    
      lightning0.AS3935_PrintAllRegs();
      
      // delay execution to allow chip to stabilize.
      delay(1000);
    
    }
    
    void loop()      
    {     
    
      // This program only handles an AS3935 lightning sensor. It does nothing until 
      // an interrupt is detected on the IRQ pin.
      while(0 == AS3935_ISR_Trig){}
     
      // reset interrupt flag
      AS3935_ISR_Trig = 0;
      
      // now get interrupt source
      uint8_t int_src = lightning0.AS3935_GetInterruptSrc();
      if(0 == int_src)
      {
        Serial.println("Unknown interrupt source");
        //gw.send(msgDist.set(999));
        //gw.send(msgInt.set(0));
      }
      else if(1 == int_src)
      {
        uint8_t lightning_dist_km = lightning0.AS3935_GetLightningDistKm();
        uint32_t lightning_intensity = lightning0.AS3935_GetStrikeEnergyRaw();
    
        Serial.print("Lightning detected! Distance to strike: ");
        Serial.print(lightning_dist_km);
        Serial.println(" kilometers");
        Serial.print("Lightning detected! Lightning Intensity: ");
        Serial.println(lightning_intensity);
        gw.send(msgDist.set(lightning_dist_km));
        gw.send(msgInt.set(lightning_intensity));
      }
      else if(2 == int_src)
      {
        Serial.println("Disturber detected");
        //gw.send(msgDist.set(998));
        //gw.send(msgInt.set(0));
      }
      else if(3 == int_src)
      {
        Serial.println("Noise level too high");
        //gw.send(msgDist.set(997));
        //gw.send(msgInt.set(0));
      }
    }
    
    // this is irq handler for AS3935 interrupts, has to return void and take no arguments
    // always make code in interrupt handlers fast and short
    void AS3935_ISR()
    {
      AS3935_ISR_Trig = 1;
    }
    

    It seems to be working (based on what I'm seeing using the serial monitor) and updating my controller (HomeSeer), although hard to know how well it's working without lightning in the area. I'll have to find a way to simulate lightning.

    I have both the lightning sensor and the radio hooked up to the SPI bus.

    Nano with NRF24L01 and AS3935_bb.png

    Cheers
    Al

    EDIT: The diagram above is incorrect, I had to connect the lightning sensor breakout board to 5V, it did not seem to work at 3.3V in this configuration.


  • Admin

    Sweet. Would you want to create a pull request when you're ready with this example (including AS3935 library)?


  • Hero Member

    @hek Thanks and yes, will do.


  • Hero Member

    @hek The AS3935 Sensor also registers the energy intensity. What sensor type would be the best way to send that data to the controller? I'm using S_DISTANCE for the calculated distance, but would also like to capture the energy intensity. The energy intensity is returned as a 32 bit integer.

    Also, the AS3935 returns the distance in km, but I believe S_DISTANCE is in cm. Is there a way to specify different units or should I have the sketch convert it to cm and then have the controller convert back to km?

    Thanks
    Al


  • Admin

    Oh.. than sensor is more advanced than I thought.

    Send distance in "meter" for now. Stupid thing that the distance sensor example we're sending in cm in the first place.

    Energy intensity is harder. What unit that is that? Maybe you could send it in VAR_1 for now?


  • Hero Member

    @hek The sensor has a number of registers that can be set and/or read, so depending what someone wants to do with it, additional parameters may be sent.

    Ok, will do regarding the units. The energy intensity is just a relative value with no units associated with it. I saw one sketch for a different breakout board for the same chip that converted the intensity to a value in the range of 1-10. The actual value returned can be as large as 16843008. I'll take a look at VAR_1, but don't believe the HomeSeer plugin supports that yet. As a test I used I used V_WATT/S_POWER for now.

    Cheers
    Al



  • @Sparkman

    If you can give me some time say around June or July, I'll be going to a tropical country with lots of lightning. I could test it out for you using Vera.


  • Hero Member

    @jeylites Thanks, I appreciate the offer. July/August are prime thunderstorm season where I live and they are forecasting a possible thunderstorm for today, so I'm hoping to confirm that everything is working today ๐Ÿ™‚

    Cheers
    Al



  • I put one of these together a short while ago -- just missed a storm rolling though, but another round might come through later. There's a reference in the code to AS3935_CAPACITANCE and a comment suggesting it be set to "THE NUMBER LISTED ON YOUR BOARD", however I'm seeing no number listed on the board. Am I just over looking it or is it something you derive?

    thanx,
    JpS


  • Hero Member

    @soward So far the thunderstorms have skirted our area, but more to come tonight. Here's hoping ๐Ÿ˜‰

    The Capacitance value is written on the bag the sensor came in. If you don't have the bag anymore, send an email to TechnicalSupport@PlayingWithFusion.com and they should be able to cross reference your order and provide the value. How does your sketch compare to mine?

    Cheers
    Al



  • @Sparkman great thanx, I do have the bag somewhere in the pile-of-parts-bags. So far I have only used the demo sketch from playingwithfusion, but once it appears to detect something I'll probably use yours as a base and branch out form there. I'm using a Vera so I can try to use VAR_1 as hek suggested.


  • Plugin Developer

    Also, the AS3935 returns the distance in km, but I believe S_DISTANCE is in cm. Is there a way to specify different units or should I have the sketch convert it to cm and then have the controller convert back to km?

    The actual value returned can be as large as 16843008. I'll take a look at VAR_1, but don't believe the HomeSeer plugin supports that yet. As a test I used I used V_WATT/S_POWER for now.

    Two mechanisms have been implemented in the HomeSeer controller plugin (1.0.5574.17274) to support custom unit strings in the controller UI:

    • V_UNIT_PREFIX (only available in the development branch of the MySensors library). The prefix provided in the V_UNIT_PREFIX message will precede the default metric unit (defined by the plugin e.g. m (meter) for the distance sensor). The sensor configuration (metric/imperial) can be set by the user as a property on S_ARDUINO_NODE device via the HomeSeer UI. Please note, the prefix will not take effect when the sensor configuration is set to imperial.
    • A user defined unit string. A unit string can be defined by the user. The metric/imperial configuration unit string and unit prefix will be ignored if a user defined unit string exists. The user defined unit string can be set by the user as a property on the device e..g. S_DISTANCE via the HomeSeer UI.

    The HomeSeer MySensors plugin is available here.

    Best regards,
    Henrik


  • Hero Member

    @hleidecker Thanks Henrik!


  • Hero Member

    Hi all,

    Well I was finally home when a thunderstorm rolled through and I was able to test the sensor and the sketch. Even though the sensor appeared to be working at 3.3V, I had to change it to 5V to get it to work properly with the USB powered Nano I have it connected to. I modified the sketch slightly (updated in my earlier post) to no longer send data when disturbers or unknown interrupt sources were detected. It's working great now and just need to put it into a case. I may use a different Arduino as well.

    Cheers
    Al


  • Hero Member

    @hek said:

    Sweet. Would you want to create a pull request when you're ready with this example (including AS3935 library)?

    Hi Henrik,

    Pull request submitted. Hopefully I did it correctly.

    Cheers
    Al


  • Admin

    Nice that you finally got some lightings to test your sketch.

    Pull request looks all ok!



  • Is it possible to detect the distance to the lightningstrike?
    I was thinking to get some sort of detector to notify me if there is ligning registered X km away from my home.



  • @Tore-Andrรฉ-Rosander

    You would need a sound detector for the thunder. Time (in milliseconds) between lightning and thunder times 0.34[m].

    Same as you would do it with your own sensors (eyes and ears) ๐Ÿ™‚

    BR,

    Boozz


  • Hero Member

    @Tore-Andrรฉ-Rosander Yes, the sensor can detect the distance. See the details of the sensor here: http://playingwithfusion.com/productview.php?pdid=22&catid=1001. Although I'm starting to believe that it's actually a lightning repeller rather than a lightning sensor as we've had very little lightning in our area after I installed it ๐Ÿ˜†

    Cheers
    Al



  • I found a similar sensor in the UK and added this to the list of my to be sensors for the weatherstation. Can I use it inside or it has to be placed outside to have a direct vision?

    http://www.embeddedadventures.com/as3935_lightning_sensor_module_mod-1016.html



  • @alexsh1 What i read when researching this chip it can be placed inside.

    @Sparkman Nice, i see that it has a detection range about 40km so thats already a pretty good distance to get a notification when lightning is detected.



  • @Sparkman I suppose your wiring diagram above is correct? I noted that the sensor is not working with 3.3V. Did you manage to find what the problem was? Looking at the datasheet http://www.embeddedadventures.com/datasheets/MOD-1016_hw_v8_doc_v4.pdf I can see what the module can operate down to 2.4V

    I am going to receive the sensor in a few days and test it.

    As I have a different module manufacturer, I may need to change the sketch as it uses a different library. This is unmodified example sketch:

    */
    
    // AS3935 MOD-1016 Lightning Sensor Arduino test sketch
    // Written originally by Embedded Adventures
    
    
    #include <Wire.h>
    #include <AS3935.h>
    
    #define IRQ_pin 2
    
    volatile bool detected = false;
    
    void setup() {
      Serial.begin(115200);
      while (!Serial) {}
      Serial.println("Welcome to the MOD-1016 (AS3935) Lightning Sensor test sketch!");
      Serial.println("Embedded Adventures (www.embeddedadventures.com)\n");
    
      Wire.begin();
      mod1016.init(IRQ_pin);
     
      //Tune Caps, Set AFE, Set Noise Floor
      //autoTuneCaps(IRQ_pin);
      
      mod1016.setTuneCaps(7);
      mod1016.setOutdoors();
      mod1016.setNoiseFloor(5);
      
      
      Serial.println("TUNE\tIN/OUT\tNOISEFLOOR");
      Serial.print(mod1016.getTuneCaps(), HEX);
      Serial.print("\t");
      Serial.print(mod1016.getAFE(), BIN);
      Serial.print("\t");
      Serial.println(mod1016.getNoiseFloor(), HEX);
      Serial.print("\n");
    
      pinMode(IRQ_pin, INPUT);
      attachInterrupt(digitalPinToInterrupt(IRQ_pin), alert, RISING);
      Serial.println("after interrupt");
    }
    
    void loop() {
      if (detected) {
        translateIRQ(mod1016.getIRQ());
        detected = false;
      }
    }
    
    void alert() {
      detected = true;
    }
    
    void translateIRQ(uns8 irq) {
      switch(irq) {
          case 1:
            Serial.println("NOISE DETECTED");
            break;
          case 4:
            Serial.println("DISTURBER DETECTED");
            break;
          case 8: 
            Serial.println("LIGHTNING DETECTED");
            printDistance();
            break;
        }
    }
    
    void printDistance() {
      int distance = mod1016.calculateDistance();
      if (distance == -1)
        Serial.println("Lightning out of range");
      else if (distance == 1)
        Serial.println("Distance not in table");
      else if (distance == 0)
        Serial.println("Lightning overhead");
      else {
        Serial.print("Lightning ~");
        Serial.print(distance);
        Serial.println("km away\n");  
      }
    }
    

    This is SPI sketch, I'd like to use I2C connection. Generally, the procedure is as follows:

    Wait a few milliseconds for the system to stabilise
    ๏‚ท Set the tune capacitor to the value indicated on the packaging, by setting the
    TUNE_CAP bits of register 8
    ๏‚ท Wait 2 milliseconds
    ๏‚ท Callibrate RCO by:
    o Sending a calibrate RCO direct command (set memory location 0x3d to the
    value 0x96)
    o Set Register 0x08, bit 5 to 1
    o Wait 2 milliseconds
    o Set Register 0x08, bit 5 to 0
    The factory calibrating tuning cap value will be fine for general use. When you have a
    MOD-1016 in an enclosure or close to other electronics it is worth calibrating the tuning
    cap again.


  • Hardware Contributor

    can't wait to test this one too ๐Ÿ˜‰ i have pcbs for a weather shield (with bme280, veml6070 etc. ) and i have this sensor on it too (https://forum.mysensors.org/uploads/files/1459631385870-stacked.jpg). But not assembled yet, was busy, i hope asap.. i plan to use it with 3v and i2c. @alexsh1 There are libs for i2c if you want ๐Ÿ™‚

    Thx @Sparkman for your work on it ๐Ÿ˜‰



  • @scalz yes, please (for i2c lib). What is this red board you have?


  • Hero Member

    @alexsh1 @scalz

    I'm running my sketch with I2C now, rather than SPI. I found the sensor would lock up occassionally, so recently converted it and am still testing it. I have mine running at 5v now as well instead of 3.3v, but it works fine with either.

    I'll post an updated sketch (and wiring diagram) soon. I based both the spi and i2c sketches on the examples found here: http://playingwithfusion.com/productview.php?pdid=22&catid=1001.

    Cheers
    Al



  • @Sparkman Thanks. Your sketch is very much appreciated. I'll have to adopt it anyway as I have a different manufacture and there is a certain process I have to follow to get it initiated (posted above).



  • Absolutely delighted with the module I have received today by post. The weather is sh@t tonight (lightning, rain etc.) which means that I can test it:

    Welcome to the MOD-1016 (AS3935) Lightning Sensor test sketch!
    TUNE	IN/OUT	NOISEFLOOR
    6	10010	5
    
    after interrupt
    DISTURBER DETECTED
    DISTURBER DETECTED
    DISTURBER DETECTED
    DISTURBER DETECTED
    DISTURBER DETECTED
    LIGHTNING DETECTED
    Lightning ~27km away
    
    DISTURBER DETECTED
    DISTURBER DETECTED
    LIGHTNING DETECTED
    Lightning ~17km away
    
    DISTURBER DETECTED
    LIGHTNING DETECTED
    Lightning ~10km away
    

    I calibrated the sensor and put a reasonable "noise floor". Now I have to convert it into MySensors and hook up to the ceech board outside.

    @Sparkman I have my sensor running at 3.3V



  • BTW, I am not sure the sensor is similar to what you guys have.

    0_1466633381738_2016-06-22 09.54.18.jpg


  • Hero Member

    @alexsh1 It looks to be a different breakout board, but for the same chip. So I would expect them to work basically the same.

    Cheers
    Al



  • @Sparkman it is a different board made (or designed) by a UK company.

    We are having a real British summer over here :-)))

    LIGHTNING DETECTED
    Lightning ~20km away
    
    LIGHTNING DETECTED
    Lightning ~20km away
    
    LIGHTNING DETECTED
    Lightning ~6km away
    
    LIGHTNING DETECTED
    Lightning ~6km away
    
    LIGHTNING DETECTED
    Lightning ~6km away
    
    LIGHTNING DETECTED
    Lightning ~6km away
    
    LIGHTNING DETECTED
    Lightning ~6km away
    
    LIGHTNING DETECTED
    Lightning ~5km away
    

  • Hero Member

    @alexsh1
    There doesn't appear to be audio input to this board, nor a microphone on the board. So, how does it estimate the distance to the lightening?


  • Hero Member

    @NeverDie All these breakout boards are based on this chip: http://ams.com/eng/Products/Wireless-Connectivity/Wireless-Sensor-Connectivity/AS3935. They use a proprietary method to figure out distance and is not based on sound.

    Cheers
    Al


  • Hero Member

    @Sparkman said:

    @NeverDie All these breakout boards are based on this chip: http://ams.com/eng/Products/Wireless-Connectivity/Wireless-Sensor-Connectivity/AS3935. They use a proprietary method to figure out distance and is not based on sound.

    Cheers
    Al

    Any impression yet as to how accurate its distance estimates are?


  • Hero Member

    @NeverDie No, as we've had very little lightning since I started using it.



  • @NeverDie Al, was quicker replying to your question. ๐Ÿ™‚
    yes, I think it is accurate for my needs - if a lightning detected at, say, 10km+/- 1km this is ok. How accurate do you want it to be?

    This is a great technology


  • Hero Member

    @alexsh1 said:

    @NeverDie Al, was quicker replying to your question. ๐Ÿ™‚
    How accurate do you want it to be?

    I'm not sure, but more accurate than lightningmaps.com or it's a no-go. I've played with lightningmaps.com during a few thunderstorms, and although it's great for getting a general idea of lightning strike rate and density, I was surprised that it seems to miss a lot of detections entirely that both my eyes and ears have confirmed. e.g. some strikes that were big enough to rattle the windows didn't show up at all on lightningmaps. Some of the others were detected, but the map plot of the strike was wrong by maybe 10 miles or so.



  • @NeverDie I have not tested this sensor long enough, but recently we have had torrential rain, lightning, etc - you can see some data I published above. The sensor did not miss a single one. There are a few parameters you can alter (noise floor). One has to setup it correctly. I have not started looking into converting the sketch for MySensors yet



  • I have adopted the MOD-1016 module (https://www.embeddedadventures.com/datasheets/MOD-1016_hw_v8_doc_v4.pdf) for MySensors if anyone is interested:

    /*
    
    Copyright (c) 2016, Embedded Adventures
    All rights reserved.
    
    Contact us at source [at] embeddedadventures.com
    www.embeddedadventures.com
    
    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
    
    - Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    
    - Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    
    - Neither the name of Embedded Adventures nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.
     
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 
    THE POSSIBILITY OF SUCH DAMAGE.
    
    */
    
    // Enable debug prints to serial monitor
    #define MY_DEBUG 
    
    // Enable and select radio type attached
    #define MY_RADIO_NRF24
    //#define MY_RADIO_RFM69
    #define MY_NODE_ID 15
    
    #include <Wire.h>
    #include <MySensors.h>
    #include <AS3935.h> // AS3935 MOD-1016 by Embedded Adventures
    
    volatile bool detected = false;
    
    
     //-----------------IMPORTANT--------------------
     //---------------CHANGE SETTINGS HERE-----------
    #define IRQ_pin 2
    
    #define AS3935_TUNE_CAPS     6 // <-- SET THIS VALUE TO THE NUMBER LISTED ON YOUR BOARD 
    #define AS3935_INDOORS       1 // AS3935_INDOORS=1 indoors, AS3935_INDOORS=0 outdoors
    #define AS3935_NOISE_FLOOR   6
    #define AS3935_ENABLE_DISTURBERS 1 // 0 or 1      
    
    #define CHILD_ID_DISTANCE 1
    #define CHILD_ID_INTENSITY 2
    MyMessage msgDist(CHILD_ID_DISTANCE, V_DISTANCE);
    MyMessage msgInt(CHILD_ID_INTENSITY, V_VAR1);
    
    void setup()  
    { 
      Serial.begin(115200);
      while (!Serial) {}
      Serial.println("MOD-1016 (AS3935) Lightning Sensor");
      Serial.println("beginning boot procedure....");
      
      Wire.begin();
      mod1016.init(IRQ_pin);
     
     //-----------------IMPORTANT--------------------
     //---------------CHANGE SETTINGS HERE-----------
      //Tune Caps, Set AFE, Set Noise Floor
      //autoTuneCaps(IRQ_pin);
      mod1016.setTuneCaps(AS3935_TUNE_CAPS);
    delay(2);
    #if AS3935_INDOORS == 1
      mod1016.setIndoors();
      #else
      mod1016.setOutdoors();
    #endif
    delay(2);
    mod1016.setNoiseFloor(AS3935_NOISE_FLOOR);
    delay(2);
    #if AS3935_ENABLE_DISTURBERS == 1
      mod1016.enableDisturbers();
    #else
      mod1016.disableDisturbers();
    #endif
    //mod1016.calibrateRCO();
    delay(2);
      Serial.println("TUNE\tIN/OUT\tNOISEFLOOR");
      Serial.print(mod1016.getTuneCaps(), HEX);
      Serial.print("\t");
      Serial.print(mod1016.getAFE(), BIN);
      Serial.print("\t");
      Serial.println(mod1016.getNoiseFloor(), HEX);
      Serial.print("\n");
    
      pinMode(IRQ_pin, INPUT);
      attachInterrupt(digitalPinToInterrupt(IRQ_pin), alert, RISING);
      Serial.println("after interrupt");
        // delay execution to allow chip to stabilize.
      delay(1000);
    
    }
    
    void presentation()  {
      // Send the sketch version information to the gateway and Controller
      sendSketchInfo("Lightning Sensor MOD-1016", "1.0");
    
      // Register all sensors to gw (they will be created as child devices)
      present(CHILD_ID_DISTANCE, S_DISTANCE);
      present(CHILD_ID_INTENSITY, S_CUSTOM);
    }
    
    void loop() {
      if (detected) {
        translateIRQ(mod1016.getIRQ());
        detected = false;
      }
    }
    
    void alert() {
      detected = true;
    }
    
    void translateIRQ(uns8 irq) {
      switch(irq) {
          case 1:
            Serial.println("Noise detected");
            break;
          case 4:
            Serial.println("Disturber detected");
            break;
          case 8: 
            Serial.println("Lightning detected!");
            printandsendToGW();
            break;
    
      }
    }
    
    void printandsendToGW() {
      int distance = mod1016.calculateDistance();
      unsigned int lightning_intensity = mod1016.getIntensity();
      if (distance == -1)
        Serial.println("Lightning out of range");
      else if (distance == 1)
        Serial.println("Distance not in table");
      else if (distance == 0)
        Serial.println("Lightning overhead");
      else {
        Serial.print("Lightning ~");
        Serial.print(distance);
        Serial.println("km away\n");
        Serial.print("Lightning Intensity: ");
        Serial.println(lightning_intensity);  
        send(msgDist.set(distance));
        send(msgInt.set(lightning_intensity));
      }
    }
    

    You have to change the sketch according to your module settings



  • I ordered one form embedded adventures on 27/7 - Now it is 3/9 and still nothing.
    Waiting to hear from them....
    That's the whole truth.



  • @skywatch give them a call or send a e-mail. Maybe your order was lost in post. Happens.
    My order arrived in 2 days from Embedded Adventures



  • OK - finally got board, seems the problem was in the warehouse. I got email to say it had been sent and it never did. At least I can try it out soon and see how it compares to the current lightning sensors I use.



  • @alexsh1
    Is your example using I2C or SPI? I can't make it out.
    I'd guess I2C, but want to make sure first.....

    Thank you


  • Hero Member

    @skywatch said in Sketch for Lightning Sensor:

    see how it compares to the current lightning sensors I use.

    Please do let us know how it compares and which one you like the best.



  • @neverdie Last night was the first lightning to test it out - 3 storm cells went through with hail and lightning, but nothing from the sensor ๐Ÿ˜ž

    So today I have rewired it, made some changes to the program and if we get lightning tonight I might have some news ๐Ÿ™‚


  • Hardware Contributor

    @skywatch said in Sketch for Lightning Sensor:

    @neverdie Last night was the first lightning to test it out - 3 storm cells went through with hail and lightning, but nothing from the sensor ๐Ÿ˜ž

    So today I have rewired it, made some changes to the program and if we get lightning tonight I might have some news ๐Ÿ™‚

    I have the same problem. Insane storms, and nothing from the sensor, the bast I had were events identified as noise. I've had storms around and sensor doesn't detect anything, very disappointing.
    I've tried to disconnect my laptop from main so it's not grounded (seem it can be a problem) but I still had nothing.



  • @nca78 As you might expect there was no lightning last night to test it. ๐Ÿ˜ž

    It's taken 2 years to get this far as storms are not frequent around here.

    My sensor is from Embedded Adventures, is that the same one you are using?

    I run it from 5V, it is set for 'indoors' and is placed on a window sil. I can see 'noise' if I place a laptop near to it. If I enable 'disturbers' I see them flooding in. The noise floor is set to 3 and I get no triggers at that level. Previously the noise floor was at 6.

    So for the moment I am a little frustrated/disappointed with this 'sensor'. But I have to wait for the next storm, which should be tonight or tomorrow ๐Ÿ™‚



  • @skywatch I have the same sensor for months working like a charm. Sadly I had to disable it as I had one node and several sensors interfering with each other.

    I will have to have the lightning sensor on a separate node



  • Embedded Adventures is a fake website anymore. They don't send the mod-1016 sensor.
    The website still gets payment for products but there is no shipment.
    embedded adventures is fraudulent.


Log in to reply
 

Suggested Topics

  • 1
  • 10
  • 3
  • 6
  • 2
  • 1

7
Online

11.4k
Users

11.1k
Topics

112.7k
Posts