/*
 * File:   motion_v4_0.c
 * Author: Singlefons
 *
 * Created on Okt 6, 2022, 14:45 PM
 *
 */
#include <xc.h>
#include <stdbool.h>

// CONFIG
#pragma config WDTE = OFF       // Watchdog Timer (WDT disabled)
#pragma config CP = OFF         // Code Protect (Code protection off)
#pragma config MCLRE = OFF      // Master Clear Enable (GP3/MCLR pin function is MCLR)
                                // for wake-up MCLRE must be off for minimum power consumption

#define _XTAL_FREQ 4000000      // clock frequency in Hz (preproccessor marcro))

#define Buzzer GPIObits.GP2
#define Sensor GPIObits.GP0     // "0" continuous sound after motion detected
#define Mode   GPIObits.GP1     // "1" sound when motion detected, a minuut, and stops after no motion

#define ActDelay 60              // activation delay after power on, seconds

void main(void)
{
    //init begin
    OPTION = 0b10011111;    // default 1111 1111 11xxxxxx
                            // bit 6 weak pull-ups on, 1=disable
    CMCON0 = 0b11110011;    // default 1111 1111 x1xx0xx1
    OSCCALbits.FOSC4 = 0;   // default already 0
    CMCON0bits.CMPON = 0;
    
    GPIO = 0b00000000;      // outputs off
    TRIS = 0b11111011;      // GP0 & GP1 input, GP2 output
    // init end
  
    
    //SLEEP instruction, before sleep intruction read inputs
    uint8_t Inputs;
    Inputs = GPIO;          // store settings IO's before sleep
           
    OPTION = 0b00011111;    //bit7=GPWU=0: Enable Wake-up on Pin Change bit (GP0, GP1, GP3)
       
    if (STATUSbits.GPWUF && STATUSbits.nTO) // pin change
    {
        // determine mode
        if (Mode=1)
            {
                // jumper J1 "1" sound when motion detected, a minute, and stops after no motion
                int i;
                for(i=0;i<200;++i)
                {
                    Buzzer = 1;            
                    __delay_ms(100);
                    Buzzer = 0;
                    __delay_ms(200);
                }
                
                Inputs = GPIO;
                SLEEP();
            } 
            else
            {
                // jumper J2 "0" continuous sound and stops until power off
                while(1)
                {
                    Buzzer = 1;
                }
            }
          
    }
    else
    {
        //activation delay after power on, seconds * x
        int i; 
        for(i=0;i<ActDelay;++i) { __delay_ms(1000);};
        
        Inputs = GPIO;
        SLEEP();
    }
    
    return;
}



