#include "sample.h"
#include "stdarg.h"
#include "stdlib.h"
#include "DSO.h"
#include "unistd.h"
#include "system.h"

int speed = 15;

//Ԥ
const int speed_table[25] = {
		/*00*/1, //1S
		/*01*/2, //500ms
		/*02*/5, //200ms
		/*03*/10, //100ms
		/*04*/20, //50ms
		/*05*/50, //20ms
		/*06*/100, //10ms
		/*07*/200, //5ms
		/*08*/500, //2ms
		/*09*/1000, //1ms
		/*10*/2000, //500us
		/*11*/5000, //200us
		/*12*/10000, //100us
		/*13*/20000, //50us
		/*14*/50000, //20us
		/*15*/100000, //10us
		/*16*/200000, //5us
		/*17*/500000, //2us
		/*18*/1000000, //1us
		/*19*/2000000, //500ns
		/*20*/5000000, //200ns
		/*21*/10000000, //100ns
		/*22*/20000000, //50ns
		/*23*/50000000, //20ns
		/*24*/100000000 //10ns
		};

int change_speed(uint8_t Inc_Dec)
{
	if(Inc_Dec)	//Ӳ
	{
		if(speed < 17)
			speed ++;
	}else	//Ͳ
	{
		if(speed > 0)
			speed --;
	}
	set_sample_speed(speed_table[speed]);
	return speed_table[speed];

}


//ò
void set_sample_speed(int speed) {
	int speed_word;

	if (speed == 100000000) {
		speed_word = 0;
	} else {
		speed_word = 100000000 / speed - 1;
	}

	IOWR(PIO_SFREQ_BASE, 0, speed_word); //òΪ50M
}


void set_trig_level(int16_t level)
{
	POINT_COLOR = GREEN;
	BACK_COLOR = BLUE;
	level = level * 2 * 16;
	IOWR(PIO_TRIG_SET_BASE, 0, level | 0x8000); //ôģʽΪͨBѹΪ0V

	char tmp[8];

	level = 3300*level/4096;
	sprintf(tmp, "%dmV  ", level);
	BACK_COLOR = BLACK;
	LCD_ShowString(730,430,16,tmp);

}

void sample_init(void) {
	set_sample_speed(speed_table[speed]); //òΪ500K
	IOWR(PIO_TRIG_SET_BASE, 0, 100 | 0x8000); //ôģʽΪͨBѹΪ0V

	IOWR_MASTER_WR_CTRL_ADDR(MASTER_WR_CTRL_BASE, DATA_MEM_BASE);
	//ָݴ洢λΪƬRAM
	IOWR_MASTER_WR_CTRL_LENGTH(MASTER_WR_CTRL_BASE, 1024*2);
	//ָΪ2048ֽ
}

void start_sample() {
	//תʹź10һ壬ת
	IOWR(PIO_EN_BASE, 0, 1);
	IOWR(PIO_EN_BASE, 0, 0);
}

int get_sample_state() {
	//ȡ״̬Ĵ
	return IORD(PIO_STATE_BASE, 0);
}

unsigned long BCD2HEX(unsigned long bcd)
{
  unsigned long temp;
  temp = (

	   + ((bcd>>12) & 0x000f) * 1000)
       + (((bcd>>8) & 0x000f) * 100)
       + (((bcd>>4) & 0x000f) * 10)
       + (bcd& 0x000f);
  return temp;
}

int update_freq()
{
	int freq;
	int freq_bin;
	int a[20];
	freq = IORD(PIO_FREQ_BASE, 0);

	freq_bin = BCD2HEX(freq);
	sprintf(a,"Freq(1)=%dHz  ",freq_bin);
	textbox5.str = a;
	updata_textbox(&textbox5);
}



void update_voltage()
{
	int Vmid;
	char a[15];
	int32_t Vmax,Vmin;
	int16_t Vpp;

	Vmin = IORD(PIO_VMAX_VMIN_BASE, 0);

	Vmax = Vmin >> 16;
	Vmin = Vmin & 0x0000ffff;
	Vpp = Vmax - Vmin;

	Vpp = Vpp * 3340 / 256;
	sprintf(a,"Vpp: %dmV  ",Vpp);
	textbox2.str = a;
	updata_textbox(&textbox2);
}
