//#####################
//⑥ メイン関数 (main.c)
//#####################
#include "main.h"
#include "debug.h"

// 外部関数のプロトタイプ宣言
void IO_Config(void);
void Timer4_Init(void);
void LCD_Init(void);
void LCD_Display_Update(SystemParams * params);
void Calculate_BPF_Coeffs(float f0, float bw, int stages);
uint16_t Read_ADC(uint8_t ch);

SystemParams global_params;
volatile uint8_t lcd_update_flag = 0; // 200msフラグ

int main(void) {
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);

//    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
    SystemCoreClockUpdate();
    Delay_Init();
    USART_Printf_Init(115200);
    printf("SystemClk:%d\r\n", SystemCoreClock);
    printf( "ChipID:%08x\r\n", DBGMCU_GetCHIPID() );
    printf("This is printf example\r\n");

global_params.f0  = 1500;
global_params.bw  = 1500;
global_params.sgc = 1500;

    IO_Config();
    LCD_Init();
//    Timer4_Init(); // 割り込みスタート
        LCD_Display_Update(&global_params);

    while(1) {
// GPIOB->BSHR = (1 << 7);              //OSC PB7 SET (0->1)66ns 
        // --- メインループで可変抵抗(ADC)の値を定期スキャン ---
        if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_5) == Bit_SET){
            // (1) F0: PA0 (ADC_Channel_0) -> 500〜1500Hz
            uint16_t adc_f0 = Read_ADC(ADC_Channel_0);
            global_params.f0 = 500 + ((adc_f0 * 1000) / 4095);
        }

        if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_6) == Bit_SET){
             // (2) BW: PA1 (ADC_Channel_1) -> 10〜1500Hz
             uint16_t adc_bw = Read_ADC(ADC_Channel_1);
             global_params.bw = 10 + ((adc_bw * 1490) / 4095);
        }

        // (3) ATT: PA2 (ADC_Channel_2) -> 2, 4, 6, 8次
         uint16_t adc_att = Read_ADC(ADC_Channel_2);
         if(adc_att < 1024)       global_params.att_order = 2;
         else if(adc_att < 2048)  global_params.att_order = 4;
         else if(adc_att < 3072)  global_params.att_order = 6;
         else                     global_params.att_order = 8;

        if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_7) == Bit_SET){
            // (4) SGC: PA3 (ADC_Channel_3) -> 1〜1500mV
             uint16_t adc_sgc = Read_ADC(ADC_Channel_3);
             global_params.sgc = 1 + ((adc_sgc * 1499) / 4095);
        }

        // (5) GNT: PA4 (ADC_Channel_4) -> 1〜100%
        uint16_t adc_gnt = Read_ADC(ADC_Channel_4);
        global_params.gnt = 1 + ((adc_gnt * 99) / 4095);

        TIM_SetCompare1(TIM1, global_params.gnt);

        // フィルター係数をリアルタイムに再計算
        __disable_irq(); // 割り込み中の一貫性を保つため一時停止
           Calculate_BPF_Coeffs((float)global_params.f0, (float)global_params.bw, global_params.att_order);
        __enable_irq();

        // 画面描画は重いため、200msに1回程度に制限
         if(lcd_update_flag == 1) {
                 LCD_Display_Update(&global_params);
                 lcd_update_flag = 0;
         }
// GPIOB->BSHR = (1 << 23);             //OSC PB7 RSET (1->0)59ns        
        Delay_Ms(10); // スキャンの安定化

    }
}



