/**
  Generated Main Source File

  Company:
    Microchip Technology Inc.

  File Name:
    main.c

  Summary:
    This is the main file generated using PIC10 / PIC12 / PIC16 / PIC18 MCUs

  Description:
    This header file provides implementations for driver APIs for all modules selected in the GUI.
    Generation Information :
        Product Revision  :  PIC10 / PIC12 / PIC16 / PIC18 MCUs - 1.77
        Device            :  PIC16F1769
        Driver Version    :  2.00
*/

/*
    (c) 2018 Microchip Technology Inc. and its subsidiaries. 
    
    Subject to your compliance with these terms, you may use Microchip software and any 
    derivatives exclusively with Microchip products. It is your responsibility to comply with third party 
    license terms applicable to your use of third party software (including open source software) that 
    may accompany Microchip software.
    
    THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER 
    EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY 
    IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS 
    FOR A PARTICULAR PURPOSE.
    
    IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, 
    INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND 
    WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP 
    HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO 
    THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL 
    CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT 
    OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS 
    SOFTWARE.
*/


#include "mcc_generated_files/mcc.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "mcc_generated_files/lcd_lib.h"

bool increment_buton;
uint8_t buton_stat = 1;

#define encoder_A PORTBbits.RB4
#define encoder_B PORTBbits.RB5
#define firstdimming 187
int pwm= 313,lcr = 205,lcd_lcr = 0; char buf_pwm[30],buf_lcr[30],diff= 0, old_pwm = 0;
int lcr_max1 = 407;
int lcr_max2=407;
uint8_t uart_value = 0;
uint16_t lcd_pwm = 0;
bool uart_state = 0;
unsigned int i = 0;

void UARTSendString(const char* str, const uint8_t max_length){
    int i = 0;
    for (i=0 ; i<max_length && str[i]!='\0' ; i++) {
        EUSART_Write(str[i]);
    }
}

int uart_read_value;

void Bluetooth_module_config(void){  
    char* name = "s-,BLE\n";
    char* uart_transparent = "ss,c0\n";
    char* baudrate = "sb,09\n";
    char* low_power = "so,1\n";
    char* reset_ble = "r,1\n";
    
    EUSART_Write('$');__delay_ms(20);EUSART_Write('$');__delay_ms(20);EUSART_Write('$');__delay_ms(20);
    EUSART_Write('+\n');__delay_ms(20);//EUSART_Write('\n');__delay_ms(20);
    UARTSendString(name,8);__delay_ms(200);
    UARTSendString(uart_transparent,7);__delay_ms(200);
    UARTSendString(reset_ble,6);__delay_ms(200);
}

void main(void)
 {
    // initialize the device
    SYSTEM_Initialize();
    PWM3_LoadDutyValue(pwm);
    DAC1_Load10bitInputData(lcr);
    // When using interrupts, you need to set the Global and Peripheral Interrupt Enable bits
    // Use the following macros to:

    // Enable the Global Interrupts
    INTERRUPT_GlobalInterruptEnable();

    // Enable the Peripheral Interrupts
    INTERRUPT_PeripheralInterruptEnable();

    // Disable the Global Interrupts
    //INTERRUPT_GlobalInterruptDisable();

    // Disable the Peripheral Interrupts
    //INTERRUPT_PeripheralInterruptDisable();
    Bluetooth_module_config();                                                  //configuring BLE module to receive data if the module has factory settings
    uint8_t LCD_init_config[] = {0x80, 0x39,
                        0x80, 0x14,
                        0x80, 0x74,
                        0x80, 0x54,
                        0x80, 0x6F,
                        0x80, 0x0C,
                        0x80, 0x01
                        };
    
    I2C_MasterWrite(LCD_init_config, 14, LCD_Address, &status);                 //configuring LCD 
    LCD_Clear();
    LCD_Write_String("PWM control",0x80);
    LCD_Write_String("DAC control",0xC0);
    __delay_ms(2000);
    LCD_Clear();
    
    while (1){                                                                  //displaying current parameters for LCR/PWM
        lcd_pwm = (pwm*10/((4*156)/10));
        lcd_lcr = lcr*0.98;
        if(lcd_pwm<10 && lcd_pwm>= 1){
            sprintf (buf_pwm, "PWM DIM =   %d  ",(int)lcd_pwm);
        }
        else if(lcd_pwm>=10 && lcd_pwm<100){
            sprintf (buf_pwm, "PWM DIM =  %d  ",(int)lcd_pwm);
        }
        else if(lcd_pwm<1){
            switch(pwm){
                case 1:
                    sprintf (buf_pwm, "PWM DIM = 0.15");
                    break;
                case 2:
                    sprintf (buf_pwm, "PWM DIM = 0.30");
                    break;
                case 3:
                    sprintf (buf_pwm, "PWM DIM = 0.45");
                    break;
                case 4:
                    sprintf (buf_pwm, "PWM DIM = 0.60");
                    break;
                case 5:
                    sprintf (buf_pwm, "PWM DIM = 0.75");
                    break;
                case 6:
                    sprintf (buf_pwm, "PWM DIM = 0.90");
                    break;
            }
        }
        else{
            sprintf (buf_pwm, "PWM DIM = %d  ",lcd_pwm);
        }       
        if(lcd_lcr<10){
            sprintf (buf_lcr, "LCR =   %dmv",lcd_lcr);
        }
        else if(lcd_lcr>=10 && lcd_lcr<100){
            sprintf (buf_lcr, "LCR =  %dmv",lcd_lcr);
        }
        else{
            sprintf (buf_lcr, "LCR = %dmv",lcd_lcr);
        }
        LCD_Write_String(buf_pwm,0x80);
        if(lcd_pwm>=1) {LCD_Write_String("%",0x8D);}
        else{
            LCD_Write_String("%",0x8E);
        }
        
        LCD_Write_String(buf_lcr,0xC0);
        __delay_ms(10);
    }
}

void IOCBF_ISR(void) {                                                          
    
    static unsigned char oldstate_encoder;
    unsigned char state_encoder;
    IOCBFbits.IOCBF4 = 0;
    IOCBFbits.IOCBF5 = 0;
    __delay_ms(1);
    state_encoder = encoder_A | encoder_B << 1;                                 //detecting the rotating sens for the encoder
    if(oldstate_encoder == 0x00){
        if(state_encoder == 0x1){
            if(buton_stat == 1){
                if(pwm <=187){
                    pwm -=6 ;
                    lcr_max2 = pwm * 1.07 + 205;
                    if(lcr > lcr_max2) lcr = lcr_max2;                          //in case the PWM is lower than 15% LCR will decrease to have lower current spikes
                }
                else if (pwm <7){                                               //is PWM is less than 1% the decreasing step will be 0.15%
                    if(pwm < 5)     
                        pwm = 4;
                    else{
                        pwm--;
                    }
                }
                else{
                    pwm -=6;
                }               
            }
            else{
                lcr--;
                if(pwm <=187){
                    if(lcr > lcr_max2) lcr = lcr_max2;
                }
            }
        }
        else if(state_encoder == 0x2){
            if(buton_stat == 1){
                if(pwm >=7){
                    pwm += 6;
                }
                else{
                    pwm++;
                }
            }
            else{
                lcr++;
                if(pwm <=187){
                    if(lcr > lcr_max2) lcr = lcr_max2;
                }
                
            }
        }   
        if(lcr <=51) lcr = 51;                                                  //setting limits for parameters
        if(lcr >= 409) lcr = 409;
        if(pwm <=1) pwm = 1;
        if(pwm >624) pwm=624;  
        PWM3_LoadDutyValue(pwm);
        DAC1_Load10bitInputData(lcr);
        
    }
    oldstate_encoder = state_encoder;
 }

void IOCCF0_ISR(void) {                                                         //switching between PWM/LCR

    buton_stat= ~buton_stat;
    IOCCFbits.IOCCF0 = 0;
}

void EUSART_RX(void){
    
    if (uart_state == 0){
        uart_value = RC1REG;
        if(uart_value == 188 || uart_value == 200 || uart_value == 211){        //detecting the object that was pressed on the Android application
            uart_state = 1;
        }
        else{
            uart_state = 0;
        }
    }
    else{
        uart_state = 0;
        switch (uart_value){
            case 188:{
                pwm++;
                break;
            }
            case 192:{
                if((pwm <= 187)&&(lcr > 358)){
                    pwm--;
                    lcr = lcr - 0.6;
                }
                else{
                    pwm--;
                }   
                break;
            }
            case 195:{
                lcr++;
                break;
            }
            case 198:{
                lcr--;
                break;
            }
            case 200:
            {
                lcr = (RC1REG)*1.62;
                if(pwm <=187){
                    if(lcr > lcr_max2) lcr = lcr_max2;
                }
                break;
            }
            case 211:
            {
                pwm = RC1REG*2.45;
                if(pwm <=187){
                    lcr_max2 = pwm * 1.07 + 205;
                    if(lcr > lcr_max2) lcr = lcr_max2;
                }     
                old_pwm = pwm;
                break;
            }
        }
    }
    if(lcr <=51) lcr = 51;
    if(lcr >=409) lcr = 409;
    if(pwm <=1) pwm = 1;
    if(pwm >624) pwm=624;
    DAC1_Load10bitInputData(lcr);
    PWM3_LoadDutyValue(pwm);
    PIR1bits.RCIF = 0;
}