Davide Cogliati
Published © GPL3+

Automate environment management prevent lightnings damage

Control energy flow during lightning storms, take a quite weekend this time, automate safety of environment.

IntermediateFull instructions provided2 hours178
Automate environment management prevent lightnings damage

Things used in this project

Hardware components

Seeed Studio Seeed Grove-AS3935Lightning-sensor
Recently developed sensor board at Seeed Studio there is already the library in Arduino Library manager, revision 1.0.0.
×1
Self designed ServerHW rev.1.0.0 board
I designed this shield board for ARDUINO UNO or similar boards and to also use with the XIAO boards family. This board is named ServerHW because can operate hardware answers on processor commands.
×1
Seeed Studio Grove 4pin Female Jumper SKU 110990028
×1
Arduino UNO
Arduino UNO
×1
bc337 transistor
Many brands to choose from, commodity component.
×3
Buzzer KPEG204 KINGSTATE
This is what I used, but similar are good as well. You can put a light beacon if not interested to acoustic alarms.
×1
Rele type NO/NC
Used a Rele type FITRE R419D-2/ 012Z1GH, any similar can work.
×1
Resistor 1k ohm
Resistor 1k ohm
Any 1/4 Watt 5% 1 kOhm resistor can be used
×5
Electric DC motor 12 V low power < 1 W
This is for simulating a load so you can also use a Led with a 1 kOhm series resistor if you prefere to have a more cheap and easy to build demo project.
×3
Supply 12 Volt source
Use this to supply the breadboard, following schematics PDF where is the 12 V tap. This supply is also fed to the Arduino input jack for <Vin> near the USB connector for programming.
×1
LED (generic)
LED (generic)
RED led, generic 5 mm
×2
Seeed Studio XIAO SAMD21 (Pre-Soldered) - Seeeduino XIAO
Seeed Studio XIAO SAMD21 (Pre-Soldered) - Seeeduino XIAO
Can load the sketch also on the XIAO SAMD21 board and have a very compact board that can be wall installed in you home or anywhere small dimensione are imposed.
×1

Software apps and online services

Seeed Studio Seeed Fusion PCB
For professional samples of PCB in short time and excellent quality.

Hand tools and fabrication machines

Prototyping Kit, Breadboard
Prototyping Kit, Breadboard
Or similar one, useful to add components for testing circuit without soldering joints.

Story

Read more

Custom parts and enclosures

Plotted traces with Arduino plotter tool of working project

Plot show how the sensor and the board separate useful signals from noise and disturbance produced by near working electric motors or other electric activity by human.

ServerHW board mounted on Arduino Uno board

Write code on Arduino Uno or XIAO board and read trough the ServerHW the sensor measures, then react trough the same board.

Animated VIDEO how the board works explaining each step.

This video demonstrates trough sequential steps how the board works when connected to Grove-AS3935Lightning-sensor capable to alarm upon Lightning front storm (here was simulated a Lightning) and make decisions in sequentially turning off equipment.

Project layout with all components described

This page show with different colors the parts making the project work and simulating an automated system called to operate when a storm is approaching and Lightning are near enough to the final user.

Schematics

ServerHW board mounted on Arduino Uno board connected to Grove sensors

Very easy connection to external loads to experiment with breadboard before making a final circuit.

Code

Automate-LIGHTNING-ALARM2.ino

Arduino
Load this project trough Arduino GUI to an Arduino UNO board upon there is the ServerHW board and build the electric schematics in the project documents to see it work. If you don't have the ServerHW board you can use the #pin numbered for Arduino board in schematics to control devices you connect your own. The SW of the sketch still works with Grove-AS3935Lightning-sensor.
//*********************************************************************************
//***************  Designed for:                                *******************
//***************  GROVE   FRANKLYN LIGHTNING SENSOR AS3935     *******************
//***************  front of lightning fall detection sensor     ******************* 
//***************                                               *******************
//*************** first release: 1.0.0 - 01/02/2023             ******************* 
//*************** Author: Davide Cogliati                       *******************
//*********************************************************************************
//                                                                        *********
//                            TITLE OF PROJECT:                           *********
//    AUTOMATE PROTECTION ACTIONS AGAINST INJURIES FOR LIGHTNING STRIKING *********
//                                                                        *********
//*********************************************************************************
//Abstract on the work:
//------------------------------------------------------------------------------------------------------
//This GROVE Sensor board integrates the AS3935 a programmable fully integrated Lightning
//Sensor IC that detects the  approach of lightning activity in the vicinity and provides an
//estimation of distance to the head of the storm. In the AS3935 there is an embedded lightning
//algorithm that checks the incoming signal form during time and rejects the potential man-made 
//disturbers as false alarms.
//The AS3935 can also provide information on the noise level and inform the external microcontroller  
//in case of high  noise conditions, with the noise floor generator and noise floor  evaluation blocks. 
//These latter functions are  programmable via the internal registers to optimize the working on 
//field of the sensor itself (INDOOR, OUTDOOR).
//The AS3935 can be programmed via IC or a 4-wire standard SPI. Also along with IC it is possible to 
//choose among three different addresses (0X01, 0X02, 0X03). 
//The board results very sensitive to electromagnetic fields so accidental peaks or false lightnings can be 
//revealed, of course the setup of the internal registers can optimize the false triggering events. 
//If a microprocessor is connected to the board via the  IC bus and the IRQ pin provided on the board the 
//lightning alarms can be managed in the best way achieving also a filtering on the events writing an 
//appropriate algorithm.
//The board is connected to the Designed shield board ServerHW that integrates all is need to interface 
//to an Arduino Uno in piggyback mode or carry the XIAO Seeed Studio alone. Both can be present making
//this duo versatile and powerful in tasking, or using the XIAO WiFi module to send remote messages
//to a node. 
//The ServerHW designed board can control external power systems or electric motors, alarms or other
//functions just using the onboard relais. This board can interface up to 3 module running in I2C
//mode so can connect to  Wio Terminal from Seeed Studio plus other sensors.
//This sketch was prepared after many test to find weak points in working and all was done
//in this direction, of course a lot of functions can be added or made better looking, but
//this will need major efforts and imagination. Just started !
//
//
//********************************************************************************
//********************************************************************************
//********************************************************************************

#include <GROVEAS3935.h>  //Library include statement (go to Library Manager Arduino)

GROVEAS3935   Sensor;     //scope declaration of the functions and variables Public 
                          //in the library declared "Sensor"

#define Device_adress 3    //IMPORTANT, sensor comunicating trough I2C need to set a 
                           //HW address.  the Grove-AS3935Lightning-sensor use this 
                           //comunication mode (can also work with SPI).
                           //HW programmed I2C Device address, by default is = 3.

//--------------------------------------------------------------------------------
//IMPORTANT NOTE:
//--------------------------------------------------------------------------------
//DEFINE where the sensor is positioned, INDOOR or OUTDOOR ?
//refere to the Arduino library examples to change this mode
//--------------------------------------------------------------------------------
#define INDOOR   1     
#define OUTDOOR  0   
//--------------------------------------------------------------------------------
//Arduino pin assignment, the ServerHW board is piggyback on it.
//--------------------------------------------------------------------------------
#define Led_blu    7
#define Led_red    11
#define Led_yellow  13
#define Led_yellow0 12
#define Led_green  7
#define Buzzer  2
#define RL5  8
#define RL6 9
#define Double 10
#define Motor_on  5
#define Invert 4

#define FREEZE_LEVEL 3  //settling time to wait before reading sensor 
                        //after a Power down and successive Power up sequence.
//-----------------------------------------------------------------------------
//VERY IMPORTANT TO SEE RESULTS OUTPUT WITH ARDUINO SERIAL          -----------
//-----------------------------------------------------------------------------
//SET THE DISPLAY MODE WITH ARDUINO:
//select directly in ARDUINO GUI for "SERIAL MONITOR" or "SERIAL PLOTTING"
//----------------------------------------------------------------------------
//+) serial monitor   = data flow in legible format and variables readout
//+) serial plotting  = show  plotting of lightning events and other variables
//--------------------------------------------------------------------------------------------------------
char LITERAL_mode =0;  //0= no print data in SERIAL MONITOR,    1= yes print data on SERIAL MONITOR
char GRAPH_mode =1;    //0= no graphical data in SERIAL PLOTTER,  1= yes graphical data   SERIAL PLOTTER
//--------------------------------------------------------------------------------------------------------
int  device;  

void setup()
{
  //---------------------------------------------------------------
  //Initialize HW  I2C address of board with address found valid !
  //default = 3
  //---------------------------------------------------------------
  device = Device_adress;
  Sensor.initializeDevice(device);
  //---------------------------------------------------------------
  Serial.begin(9600); 
  Wire.begin();          // start I2C communication 
  Wire.setClock(100000); // set I2C  speed 

  if (LITERAL_mode ==1)
      {
      Serial.println("-----------------------------------------------");   
      Serial.println("Automate Lightning detection");  
      Serial.println("Grove-AS3935LIGHTNING SENSOR automation example");
      Serial.println("Starting....");
      Serial.println("-----------------------------------------------");
      delay(1000);
      }
      
   if (OUTDOOR ==1)
      {
      Sensor.setOutdoor();              //set for indoor position of sensor
      delay(1000);
      }
  if (INDOOR ==1)
      {
      Sensor.setIndoor();               //set for outdoor position of sensor
      delay(1000);
      }  
  
   //------------------------------------------
   //SET pinmode for ARDUINO - ServerHW board
   //------------------------------------------
   pinMode(RL5,OUTPUT);
   pinMode(RL6,OUTPUT);
   pinMode(Double,OUTPUT);
   pinMode(Led_green,OUTPUT);
   pinMode(Led_yellow,OUTPUT);
   pinMode(Led_yellow0,OUTPUT);
   pinMode(Led_red,OUTPUT);
   pinMode(Led_blu,OUTPUT);
   pinMode(Buzzer,OUTPUT);  
   pinMode(Motor_on,OUTPUT);
   pinMode(Invert,OUTPUT); 

  
   digitalWrite(Led_blu,LOW);        
   digitalWrite(Led_green,LOW);     
   digitalWrite(Led_yellow,LOW); 
   digitalWrite(Led_yellow0,LOW);       
   digitalWrite(Led_red,LOW);
   digitalWrite(RL5,LOW); 
   digitalWrite(RL6,LOW);       
   digitalWrite(Double,LOW);
   digitalWrite(Buzzer,LOW);  
   digitalWrite(Motor_on,LOW);
   digitalWrite(Invert,LOW); 
   //------------------------------------------
   //LED TEST OUTPUT
   //------------------------------------------    
   digitalWrite(Led_blu,HIGH);  
   delay(100);
   digitalWrite(Led_blu,LOW);  
   //
   digitalWrite(Led_green,HIGH);  
   delay(100);
   digitalWrite(Led_green,LOW); 
   //
   digitalWrite(Led_yellow,HIGH);  
   delay(100);
   digitalWrite(Led_yellow,LOW); 
   //
   digitalWrite(Led_yellow0,HIGH);  
   delay(100);
   digitalWrite(Led_yellow0,LOW); 
   //
   digitalWrite(Led_red,HIGH);  
   delay(100);
   digitalWrite(Led_red,LOW); 
   //
   digitalWrite(Buzzer,HIGH);  
   delay(100);
   digitalWrite(Buzzer,LOW); 
   //---------------------------------
   digitalWrite(Buzzer,HIGH);  
   delay(100);
   digitalWrite(Buzzer,LOW); 
   digitalWrite(Led_red,HIGH);  
   delay(100);
   digitalWrite(Led_red,LOW); 
   digitalWrite(Led_yellow0,HIGH);  
   delay(100);
   digitalWrite(Led_yellow0,LOW); 
   digitalWrite(Led_yellow,HIGH);  
   delay(100);
   digitalWrite(Led_yellow,LOW); 
   digitalWrite(Led_green,HIGH);  
   delay(100);
   digitalWrite(Led_green,LOW); 
   //
   digitalWrite(Buzzer,LOW);  

}

//------------------------------------------------------------------------------------
//    MAIN LOOP RUNNING
//------------------------------------------------------------------------------------
void loop()
{
  int c;
  int i;
  int indevice;   //device number I2C address, in final application you can assign 
                  //directly the address (for example: indevice = 3;)
  int dataRead =0; 
  //---------------------------------------------------
  // read/write functions for I2C mode:
  //---------------------------------------------------
  //**************************************************************************
  //**************************************************************************
       int done =1;     //flag to start self test on I2C sensor address
       indevice = 0;    //reset address value
    
       //--------------------------------------------------------------------------
       //WAITING CYCLE - ENDLESS - LOOKING FOR LIGHTNINGS
       //variables from AS3935 during operative cycle
       //--------------------------------------------------------------------------
       int INT_struck ; //event interrupt register
       int N_lightning; //number of lightnings detected
       int Av_distance; //average distance extimation
       int NOISE; //interrupt for high noise level
       int Disturber; //interrupt for disturber detected
       int L_struck; //interrupt for lightning detected
       int Distance; //estimated hit distance
       int Energy_LSB; //energy single event LOW BYTE
       int Energy_MSB; //energy single event HIGH BYTE
       int Energy_MMSB; //energy single event AV.Energy content
       int Calculate_Intensity; //weighted LSB-MSB-MMSB
       //-------------------------------------------------
       //-------------------------------------------------
       //GRAPH SCALING MIN-MAX: MODIFY AS YOU LIKE!!!
       //-------------------------------------------------
       int  MAX_scale =30;        //setting max Y of plotting
       int  min_scale =0;         //setting min Y of plotting
       //-------------------------------------------------
       //PRINT OUT METHOD:
       //---------------------------------------------------------------------------
       //  LITERAL_mode =0;    //0= no printing data on SERIAL MONITOR
       //  GRAPH_mode   =1;    //1= yes print graphical data in SERIAL PLOTTER
       //---------------------------------------------------------------------------
       if (GRAPH_mode ==1)
      {
       //*****************************************
       //SET UP THE PLOTTER X-Y READINGS (X= time)
       //*****************************************
            Serial.print("MAX"); //max line marker
            Serial.print("  ");
            Serial.print("min");//min line marker 
            Serial.print("  ");
            //*****************************************
            //SETUP LABELS NAME
            //*****************************************
            Serial.print("NOISE");
            Serial.print("  ");
            Serial.print("Disturber");
            Serial.print("  ");
            Serial.print("Distance");
            Serial.print("  ");
            Serial.print("Energy_MSB/20");  //SCALED FACTOR /20
            Serial.print("  ");
            Serial.print("Energy_MMSB");
            Serial.print("  ");
            Serial.print("Tot.Energy");
            Serial.print("  ");
            Serial.print("p-event: ");
            Serial.print("  ");  
            Serial.println("elap.time: ");
      }
       //**************************************************
       //**************************************************
       // STARTING ENDLESS OBSERVATION CYCLE FOR EVENTS
       //**************************************************
       //**************************************************
            int P_event = 0;      //positive event, Lightning in a observation window
            int Elapsed_time =0;  //every count is 1 sampling on the sensor output
            int Noise_events=0;   //noise events captured in an observation window (Elapsed_time)
            int Dist_events=0;    //distrubance events happened in an observation window
            int freeze=0;         //this counter is for reducing load turn up interference
                                  //with the sensor if near a load.
        //-------------------------------------
        //ACTIVATE SERVICES - open SHED -------
        //-------------------------------------
        //------------------------------------------------------------
        //sequencing of systems ON, avoid inrush currents, oveloads
        //------------------------------------------------------------
        digitalWrite(Buzzer,HIGH);     
        digitalWrite(RL5,HIGH); 
        delay(2000); 
        digitalWrite(Buzzer,LOW);  
        digitalWrite(RL6,HIGH);    
        delay(2000);  
        digitalWrite(Buzzer,HIGH);   
        digitalWrite(Double,HIGH);
        delay(2000);
        digitalWrite(Buzzer,LOW);  
        //SHED OPEN 4 SEC.
        digitalWrite(Motor_on,HIGH);
        digitalWrite(Invert,LOW); 
        delay(4000);
        //----------------------------------------------------------------------
        //TURN SHED MOTOR OFF, home for shed is reached (time limited movement)
        //----------------------------------------------------------------------
        digitalWrite(Motor_on,LOW);
        digitalWrite(Invert,LOW);     
        //----------------------------------------------------------------------
        int Scan_rate = 10; // <--  SCANNING INTERVAL .... MODIFY AS NEEDED !!!
        //----------------------------------------------------------------------    
             while (1)  //END LESS LOOP you can add ESCAPE condition 
                        //if necessary to "break" out
              {
               digitalWrite(Led_blu,HIGH);  //LIVE FLASH..flashes each seconds show
                                            //activity is on: modify "Scan_rate" to change
               if (LITERAL_mode ==1)
                { 
                  Serial.println();
                  Serial.print(" *** WAITING FOR LIGHTNING - WATCHING ");         // Print the character
                  Serial.println();
                } 
              
               //------------------------------------------------------------------
               //CHECK FOR INCOMING INT MESSAGE ON REG 0X03 bit= INT_L ---> "1000"
               //------------------------------------------------------------------
              c=0;
              i= 0x03;  //interrupt INT register address
              dataRead= Sensor.readFromAS3935 (device, i); //read data from internal registers trough adr_I2C
              
              //------------------------
              //CLEAN the variables
              //------------------------
              NOISE =0 ;
              Disturber =0;
              L_struck =0 ;
              Distance =0 ;
              Energy_LSB =0 ;
              Energy_MSB =0 ;
              Energy_MMSB =0 ;
              Calculate_Intensity=0;
              //marker=3;            //kept raised to be visible
              //------------------------
              c = dataRead ;       // Receive a byte as character 
              
              INT_struck = c;
              NOISE  =INT_struck & (0b00000001);
              Disturber  =INT_struck & (0b00000100);
              L_struck  =(INT_struck & (0b00001000))/8;  //this is a flag bit so can be 0 or 1.

             if (NOISE >0)
             {
               Noise_events= Noise_events +1;
             }
             
             if (Disturber >0)
              {
                Dist_events=  Dist_events + 1;
              }
           
           //------------------------------------------------------------------------------------------------
           //DEBUG ALL !!!
           //------------------------------------------------------------------------------------------------
           // L_struck =1; --->   this show all messages, testing purpose-DEBUG of AS3935 system remove "//"
           //-------------------------------------------------------------------------------------------------
           //
          
          if ((GRAPH_mode == 1) & (L_struck ==0))
            {
            //------------------------------------------------
            //GRAPH- PLOTTER  no Lightnings to show
            //------------------------------------------------
            Serial.print(MAX_scale,DEC);
            Serial.print("  ");
            
            Serial.print(min_scale,DEC);
            Serial.print("  ");
            //------------------------------------------------
            Serial.print(0); 
            Serial.print("  ");
            Serial.print(Disturber*3,DEC); //just to make this trace enhanced on graph
            Serial.print("  ");
            Serial.print(0); 
            Serial.print("  ");
            Serial.print(0);
            Serial.print("  ");
            Serial.print(0);
            Serial.print("  ");
            Serial.print(0);
            Serial.print(" ");
            Serial.print(0);
            Serial.print(" ");
            Serial.println(0);
            } 
           //------------------------------------------------------------------------------
           //hit EVENT captured: show the result !
           //------------------------------------------------------------------------------
           if (L_struck > 0)
          {
           freeze = freeze -1;
           if(freeze <0)
            freeze=0;
           //----------------------------------------------------------------
           //distance estimation - other lightning data - energy calculation
           //----------------------------------------------------------------
           //estimated DISTANCE:
           //--------------------
            c=0;
            i= 0x07;
            dataRead= Sensor.readFromAS3935 (device, i); //read data from internal registers trough adr_I2C

            c = dataRead ;//Wire.read();    // Receive a byte as character   
            Distance = c;
            Distance  = Distance & (0b00111111);
            //--------------------------------------------
            //ENERGY content registers  LSB - MSB - MAIN
            //--------------------------------------------
            i= 0x04;
            dataRead= Sensor.readFromAS3935 (device, i); //read data from internal registers trough adr_I2C
            c=0;
            c = dataRead ;//Wire.read();    // Receive a byte as character 
            Energy_LSB = c;
            //-------------------------
            //ENERGY MSB 
            //-------------------------
              i= 0x05;
              dataRead= Sensor.readFromAS3935 (device, i); //read data from internal registers trough adr_I2C
              c=0;
              c = dataRead ;//Wire.read();    // Receive a byte as character     
               Energy_MSB = c;
    
            //-------------------------
            //ENERGY MMSB 
            //-------------------------

            i= 0x06;
            dataRead= Sensor.readFromAS3935 (device, i); //read data from internal registers trough adr_I2C
            c=0;     
            c = dataRead ;//Wire.read();    // Receive a byte as character 
      
            Energy_MMSB = c;
            Energy_MMSB  = Energy_MMSB & (0b00011111);
            Calculate_Intensity= Sensor.calculateIntensity ();//just a figure of merit on relative
                                                              //intensity of events for comparison. 

            
         if ((NOISE==0)  & (Disturber ==0) & (freeze== 0))  
            {
              //-----------------------------------------------------------
              //COUNT positive (Lightning event) in the observation window
              //-----------------------------------------------------------
               P_event = P_event + 1;  //increment positive event in an observation window
             }
          
            //--------------------------------------------------------- 
            //select type of readout FULL NUMERICAL DATA or GRAPH DATA
            //--------------------------------------------------------- 
            if (GRAPH_mode == 1)
            {
            //------------------------------------------------
            //LEGIBILE FORM OF EVENT READINGS
            //------------------------------------------------
            //SETTING UP MAX-min scale for plot
            //-----------------------------------
            Serial.print(MAX_scale);
            Serial.print("  ");
            Serial.print(min_scale);
            Serial.print("  "); 
            //------------------------------------------------
            Serial.print((NOISE*3),DEC);    // x 10 enhances the sight on the graph
            Serial.print("  ");
            Serial.print(Disturber*3,DEC);  // x 10 enhances the sight on the graph
            Serial.print("  ");
            Serial.print(Distance,DEC);
            Serial.print("  ");
            Energy_MSB = Energy_MSB/20;   //JUST A SCALING FACTOR TO PLOT !
            Serial.print(Energy_MSB,DEC);
            Serial.print("  ");
            Serial.print(Energy_MMSB,DEC);
            Serial.print("  ");
            Calculate_Intensity = Calculate_Intensity/500; //SCALING FACTOR for graph
            Serial.print((Calculate_Intensity),DEC);
            Serial.print("  ");
            Serial.print((P_event),DEC);
            Serial.print("  ");
            Serial.println((Elapsed_time),DEC); 
            } 
            if (LITERAL_mode == 1)
            {
            //------------------------------------------------
            //LEGIBILE FORM OF EVENT READINGS
            //------------------------------------------------
            Serial.println();
            Serial.println("*****************************************************");
            Serial.println();
            Serial.print("Noise LEVEL detected: ");
            Serial.println(NOISE,DEC);
            Serial.print("Disturber detected: ");
            Serial.println(Disturber,DEC);
            Serial.print("Lightining detected: ");
            Serial.println( L_struck,DEC);
            Serial.println();
            Serial.print("Estimated hit distance: ");
            Serial.println(Distance,DEC);
            Serial.print("LSB single event energy: ");
            Serial.println(Energy_LSB,DEC);
            Serial.print("MSB single event energy: ");
            Serial.println(Energy_MSB,DEC);
            Serial.print("MMSB single event energy: ");
            Serial.println(Energy_MMSB,DEC);
            Serial.print("Weighted total energy: ");
            Serial.println(Calculate_Intensity,DEC);
            Serial.print("Window total Lightning event: ");
            Serial.println((P_event),DEC);
            Serial.print("Window NOISE-events: ");
            Serial.println((Noise_events),DEC);
            Serial.print("Window DISTURB-events: ");
            Serial.println((Dist_events),DEC);
            Serial.print("Window elap.time: ");
            Serial.println((Elapsed_time),DEC);    
            Serial.print("Freeze alarm level: ");
            Serial.println((freeze),DEC);     
            } 
          //---------------------------------------------------------------------------------
          //----------------------------------
          //----------------------------------
          //----------------------------------
          //ALARMING OUTPUT - DEFINE severity
          //----------------------------------
          //
          //FILTERING OF SENSOR DATA: 2 ways to do
          //1) refine the setup of the Sensor trough internal registers;
          //2) operate on SW algorythm to verify the alarma;
          //   
          // The scope in point (1) & (2) is to adapt to the existing environment and:
          //
          //+) AVOID NOISE
          //+) AVOID DISTURBANCIES
          //+) AVOID SIMILAR LIGHTNING ACTIVITY  DUE TO HUMAN ACTIVITY
          //   (motors, ON-OFF lights, sensor touch by hands, WiFi approaching...)
          //----------------------------------------------------------------------------------
        
          //*****************************************************************************
          //3 CONDITIONS TO MAKE A DECISION TO TURN SYSTEM OFF
          //*****************************************************************************
          //1) NOISE=0      noise should be absent in the measure
          //2) Disturber=0  no disturb was sensed
          //3) freeze=0     freezing counting is zero, out of power turn ON transients
          //------------------------------------------------------------------------------
       if ((NOISE==0)  & (Disturber ==0) & (freeze== 0))  
        {  //----------------------------------
           //--------------------------------------------------
           //STATISTICAL FILTERING OF EVENTS / HUMAN ACTIVITY
           //--------------------------------------------------    
         if(Elapsed_time > 1)  //point of  starting analyzing in the window
           {
       
           if(P_event >= 1)   //threshold of lightnings (positvie events) in a fixed window
             {                //can also be managed trough setup of the sensor AS3935
                              //read datasheet AS3935_Datasheet_EN_V2.Pdf the difference
                              //is here we decide the time dimension of the time window
             if (Distance < 3)
              {
               digitalWrite(Led_red,HIGH);  
               } 
              if (Distance >=3 & Distance < 10)
               {
               digitalWrite(Led_yellow,HIGH);  
               } 
              if (Distance >=10 & Distance < 20)
               {
               digitalWrite(Led_yellow0,HIGH);  
               } 
              if (Distance >=20 & Distance < 30)
              {
               digitalWrite(Led_yellow,HIGH);  
               digitalWrite(Led_green,HIGH);  
              } 
              if (Distance > 30)
              { 
              digitalWrite(Led_green,HIGH);  
           }
        //-----------------------------------
        //turn OFF services sequencing
        //moving shed to CLOSE
        //-----------------------------------   
        digitalWrite(Buzzer,HIGH);  
        digitalWrite(RL5,LOW); 
        delay(3000);
        digitalWrite(RL6,LOW);
        delay(3000);       
        digitalWrite(Double,LOW);
        digitalWrite(Invert,HIGH); 
        delay(1000);
        digitalWrite(Motor_on,HIGH);
        delay(4000);
        digitalWrite(Buzzer,LOW);  
        //-------------------
        //STOP SHED movement
        //-------------------
        digitalWrite(Motor_on,LOW);
        delay(3000);
        //-------------------
        //-------------------------------------
        //WAITING TIME or CONDITION TO RESTART
        //-------------------------------------

        delay(5000);  //just 5 seconds to make it simple!
        //-------------------------------------
        digitalWrite(Led_yellow0,LOW);  
        digitalWrite(Led_red,LOW);  
        digitalWrite(Led_yellow,LOW); 
        digitalWrite(Led_green,LOW); 
        //-----------------------------------
        //restart all with sequencing
        //-----------------------------------
       //------------------------------------
       //ALL SERVICES ARE WORKING
       //------------------------------------
        digitalWrite(RL5,HIGH); 
        delay(2000);
        digitalWrite(RL6,HIGH); 
        delay(2000);      
        digitalWrite(Double,HIGH);
        digitalWrite(Buzzer,LOW);  
        digitalWrite(Motor_on,HIGH);
        //---------------
        //open shed
        //---------------
        digitalWrite(Invert,LOW); 
        delay(3000);   //-------------> settling time to prevent system ON inrush currents!
        //-------------------
        //STOP SHED
        //-------------------
        digitalWrite(Motor_on,LOW);
        delay(3000);   //-------------> settling time to prevent system ON inrush currents!
        //-----------------------------------
        freeze = FREEZE_LEVEL;    //this makes n.cycles readout of sensor so to flush out data altered by motor moving 
       }    
      } 
     }
       //----------------------------------------------------- 
    }  //end of (if) manager for L_struck > 0
       //-----------------------------------------------------
       //
       //------------------------------------
       //ALL SERVICES ARE WORKING ON STATE !!
       //------------------------------------
        digitalWrite(RL5,HIGH); 
        digitalWrite(RL6,HIGH);       
        digitalWrite(Double,HIGH);
        digitalWrite(Buzzer,LOW);  
       //------------------------------------
       //------------------------------------ 
        digitalWrite(Led_blu,LOW); // <--------------FLASH OFF  LIVE LED      
        delay(Scan_rate);          // <------------- SCANNING INTERVAL .... MODIFY AS NEEDED !!!
       //------------------------------------
       //
       //**************************************************************************
       //**************************************************************************
       //****** CHECKING FOR PRESENCE OF LARGE NUMBER OF DISTURBS IN A            *
       //****** FIXED TIME ("Elapsed_time") IN ORDER TO STOP SYSTEM               *
       //****** CONTROL IN CASE OF OUT OF TOLERANCE (avoid stop down not required)*
       //**************************************************************************
       //**************************************************************************
       Elapsed_time = Elapsed_time + 1; //every count= 1 sample on the sensor output
          if (Elapsed_time > 15)        //time sample window under test.
           {
             Elapsed_time =0;      //restart the observation window
             P_event = 0;          //reset count for positive event (observation window)
             Dist_events =0;       //reset counting for disturb (observation window)
             Noise_events= 0;      //reset counting for noise (observation window)
             //
             if(Dist_events>10)    //tolerated disturb threshold !
              {                    //modify as necessary..........
                  //-----------------------------------
                  //turn OFF services with sequencing
                  //HIGHLY DISTURBED ENVIRONMENT
                  //-----------------------------------  
                  //buzzer 
                  digitalWrite(RL5,LOW); 
                  delay(2000);
                  digitalWrite(RL6,LOW);       
                  delay(2000);
                  digitalWrite(Double,LOW);
                  delay(2000);
                  digitalWrite(Buzzer,LOW);  
                  digitalWrite(Motor_on,LOW);
                  digitalWrite(Invert,LOW);   
                  //---------------------------------------------------
                  //Trapping endless loop - disturbs are too high
                  //to have a good reading with sensor
                  //check installation, try to rotate sensor !
                  //Sensor is sensitive to polarization & inclination
                  //---------------------------------------------------           
               while(1)
                 {
                   digitalWrite(Buzzer,LOW); 
                   digitalWrite(Led_yellow0,LOW);  
                   digitalWrite(Led_red,LOW);  
                   digitalWrite(Led_yellow,LOW); 
                   digitalWrite(Led_green,LOW); 
                   delay(1000);
                   digitalWrite(Buzzer,HIGH); 
                   digitalWrite(Led_yellow0,HIGH);  
                   digitalWrite(Led_red,HIGH);  
                   digitalWrite(Led_yellow,HIGH); 
                   digitalWrite(Led_green,HIGH); 
                   delay(1000);           
                 } 
               } 
                  //---------------------------------------------------
                  //--- end trapping loop  ---------------------------- 
                  //---------------------------------------------------
            }  
        }

  }   
//-----------------------------------------------------------------------------
//------------------ END OF SKETCH  -------------------------------------------
//-----------------------------------------------------------------------------

Credits

Davide Cogliati

Davide Cogliati

7 projects • 6 followers
I develop electronic boards for customers and final 3D products.

Comments