#include "scan.h"
#include "bsp_rs2251.h"
#include "bsp_74hc595.h"
#include "bsp_adc.h"
#include "resi_math_lib.h"
#include "string.h"

#define ADC_DELAY_TIME (10 * 220) //9 ns * 120


void Hc4051Delay(uint32_t num)
{
    while(num --);
}



/*
   功能：行列扫描读取数据
   输入：无
   返回：返回32*64的数据
   */
void ReadAdcValue(adc_value_frame_struct *adc_raw_value,RESISTACE_NAME resistace_name)
{
	uint8_t AX_rank[] = {6,4,2,1,0,3,5,7};
	//uint8_t AX_rank[] = {7,5,3,0,1,2,4,6};
	
    if(resistace_name == RAW_RESISTACE)
    {
        for(uint8_t ax = 0; ax < 8; ++ax)
        {
            Choose_AX_Channel(AX_rank[ax]);
            Hc4051Delay(ADC_DELAY_TIME);
						
            adc_raw_value->sensorB_raw_value[ax]				= 	GetAdcValue(1);
						if(ax < 4)
						{
							adc_raw_value->sensorB_raw_value[ax + 8]	= GetAdcValue(0);
						}
        }

    }
    else
    {
        for(uint8_t ax = 0; ax < 8; ++ax)
        {
            Choose_AX_Channel(AX_rank[ax]);
            Hc4051Delay(ADC_DELAY_TIME);

            adc_raw_value->sensorB_ref_value[ax]				= 	GetAdcValue(1);
						
						if(ax < 4)
            adc_raw_value->sensorB_ref_value[ax + 8]	= GetAdcValue(0);

        }
    }


}


void scan_y(adc_value_frame_struct *adc_raw_value,uint8_t count_y)
{
static	uint8_t AY_rank[] = {7,6,5,4,3,2,1,0,15,14,13,12};//这个改先序需要用到
static  math_resi_cal_t math_resi_cal = {0};
   
    REF_OUT(1);//低扫
    ic_74hc595_clean_0(16);
    ReadAdcValue(adc_raw_value, REFER_RESISTACE);

    REF_OUT(0);
    ic_74hc595_io_write_1(AY_rank[count_y]);
    ReadAdcValue(adc_raw_value, RAW_RESISTACE);
		
    math_resi_cal.sensor_adc_value = adc_raw_value->sensorB_raw_value;
    math_resi_cal.resi_adc_value = adc_raw_value->sensorB_ref_value;
    math_resi_cal.math_number = AX_NUM;
		

    math_resi_cali_once(&math_resi_cal,
                        adc_raw_value->sensorB_resi_output,
                        AX_NUM,
                        SCAN_LOW_LEVEL);

    math_display_resi(adc_raw_value->sensorB_resi_output,
                      adc_raw_value->sensorB_display_output,
                      AX_NUM,
                      RESI_BACKWARDS);
											
		memcpy(adc_raw_value->sensorB_voltage[count_y],adc_raw_value->sensorB_display_output,AX_NUM);
}

