#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/eeprom.h>

#include <avr/sleep.h>
#include "macro.h"
//#include "trh033m.h"
#include "cc1100.h"
#include "cc1100_globals.h"
//#include <avr/iomx8p.h>
#include "spi1.h"

#include <stdint.h>
#include <avr/wdt.h>
//#include <avr/i2c.h>
#include <util/twi.h>



#define TEST				REGISTER_BIT(PORTC,0)

#define OUTPUT				REGISTER_BIT(PORTC,1) 
#define SCLR				REGISTER_BIT(PORTC,3) 
#define SCLK				REGISTER_BIT(PORTC,2) 
#define CLK					REGISTER_BIT(PORTC,4) 
#define S_DATA				REGISTER_BIT(PORTC,5) 

#define BUZZER				REGISTER_BIT(PORTD,4) 
#define TX_EN				REGISTER_BIT(PORTD,3) 


#define B_CTL				REGISTER_BIT(PORTB,0)
#define CS_CC1101			REGISTER_BIT(PORTB,2)

#define CS_CC1101_LOW			CS_CC1101 =0
#define CS_CC1101_HIGH			CS_CC1101 =1


#define B_CTL_LOW			B_CTL =0
#define B_CTL_HIGH			B_CTL =1

#define OUTPUT_HIGH			OUTPUT = 1
#define OUTPUT_LOW			OUTPUT = 0


#define SCLR_HIGH			SCLR = 1
#define SCLR_LOW			SCLR = 0

#define S_CLK_HIGH			SCLK = 1
#define S_CLK_LOW			SCLK = 0

#define CLK_HIGH			CLK = 1
#define CLK_LOW				CLK = 0

#define S_DATA_HIGH			S_DATA = 1
#define S_DATA_LOW			S_DATA = 0


/*

#define CNT_SEC		0x00;
#define CNT_MINUTES	0x01;
#define CNT_HOUR	0x02;
#define CNT_DAY		0x03;
#define 
#define 
#define 
#define 
#define 
#define 

*/





//trh_card_t card;



uint8_t status;
uint8_t	test_cnt02;
cc1101_tx_data tx_data;

u8 chk_state=0;

u8 test1;
u8 test2;
u8 test3;
volatile u8 input_data=0;

//u8 status=0;


u8 a;
u8 b;
u8 th[3]={0,0,0};
u8 tl[3]={0,0,0};
u8 t_temp[3]={0,0,0};
u8 test_temp;
u8 test_temp2;
u8 test_temp3;


enum {
	KEY_CHK=0,
	CA_OUT_SETUP,
	DATA_OUT_SETUP,
	CA_WAVEOUT,
	FIFO_SETUP,
	DATA_WAVEOUT,
	CA_KEY_CHANGE_CHK
};








#if 0

void udelay(u8 usec)
{
	register u8 i;

	for(i = 0 ;   i < usec ; i++){
		asm volatile("NOP");
		asm volatile("NOP");
		asm volatile("NOP");
		asm volatile("NOP");
	}
}


#endif




#if 1

void u100delay(u8 usec)
{
	register u8 i;

	for(i = 0 ;   i < usec ; i++){
		asm volatile("NOP");
		asm volatile("NOP");
		asm volatile("NOP");
	}
}


#endif







/*
 	mili second  Delay
*/



void mdelay(u16 msec)
{
	register u16 i;
	for(i = 0 ; i < msec  ; i++){
		u100delay(10);
	}
}




/*
void mdelay(u16 msec)
{
	register u16 i;
	for(i = 0 ; i < msec  ; i++){
		udelay(250);
		udelay(250);
		udelay(250);
		udelay(250);
	}
}
*/

void sdelay(u16 msec)
{
	register u16 i;

	for(i=0;i<msec;i++)
	{
		mdelay(1000);
	}
}







/*
 	mili second  Delay
*/




#if 1

void putc(u8 data)
{
	while(!(UCSR0A & (1<<UDRE0)));
	UDR0 = data;
}

void putb(u8 data)
{
	if(data < 0x0a)
		putc('0' + data);
	else 
		putc('a' + (data-10));
}




void puthex(u8 data)
{
	putb(data/16);
	putb(data%16);
}


void timer_init()
{
	TCCR1A = 0x00;
	TCCR1B = 0x0a;
	TCCR1C = 0x00;
	OCR1A  = 0xffff;
	TCNT1  = 0x0000;

	TCCR0B=(1<<CS02)|(1<<CS00);		//clkI/O/1024 (From prescaler)		(15625hz) 		1/(1000000/64)  = 	64us..
	TCNT0=0;

}

#endif


void inituart()
{
	//UCSR0A = 0x00;
	UCSR0A = 0x02;	//U2X = 1
	UCSR0B = 0x00; // Rx/Tx enable

	UCSR0C = 0x06; // 8bit, 1 stop bit, no parity

	UBRR0H = 0x00; 
	//UBRR0L = 51; // Baudrate 9600
	//UBRR0L = 0x35; // Baudrate 300
	//UBRR0L = 0x34; // Baudrate 300
	//UBRR0L = 0x33; // Baudrate 300
	//UBRR0L = 0x0d; // Baudrate 1200
	UBRR0L = 0x0c; // Baudrate 1200
	//UBRR0L = 64; // Baudrate 9600

	UCSR0B = 0x98; // rx / tx enable , rx int enable 0x98
}


unsigned char ctrl[3]={0x00,0x00,0x00};





#define OVERFLOW 256  

#define TICKS_PER_SEC 1000  

#define Prescaler 64  


volatile unsigned int tic_time;  
volatile unsigned int c_read_time;
    

//u8 ms240=0;


//u8 led_ctl=0x01;
//u8 led_change=0;
//u8 led_start=0x01;


char ms33=0;
ISR(TIMER0_OVF_vect)
{
	test_cnt02++;


}  

ISR(TIMER2_OVF_vect)
{
	u8 i;

	test_cnt02++;
	TCNT2=0;

	#if 0
	for(i=0;i<5;i++)
	{
		B_CTL_LOW;
		mdelay(100);
		B_CTL_HIGH;
		mdelay(100);
	}
	#endif


}  


void hw_setup(void)
{

    DDRC=0x00;      
	DDRD=0x00;
	DDRB=0x0D;
	//DDRB=0x2c;

	//TCCR0B=(1<<CS02)|(1<<CS00);		//clkI/O/1024 (From prescaler)		(15625hz) 		1/(1000000/64)  = 	64us..
	//TCNT0=(256-78);
	//TIMSK0 |= (1<<TOIE0);

	/*pull_up*/
	PORTC = (1<<PC0) | (1<<PC1);
	PORTD = 0xf3;





	#if 1

	/*Timer2 test*/
	TCCR2B=(1<<CS22)|(1<<CS21)|(1<<CS20);		//clkI/O/1024 (From prescaler)		(15625hz) 		1/(1000000/64)  = 	64us..
	TCNT2=0;
	TIMSK2 |= (1<<TOIE2);

	#endif


	//set_sleep_mode(SLEEP_MODE_PWR_DOWN);


	EICRA &= ~(1<<ISC00);	//INT0の割り込み発生条件を立下り検知でトリガで固定
	EICRA &= ~(1<<ISC01);

	EICRA &= ~(1<<ISC10);	//INT1の割り込み発生条件を立下り検知でトリガで固定
	EICRA &= ~(1<<ISC11);



	EIMSK |= (1<<INT0);
	EIMSK |= (1<<INT1);




}





uint8_t cc1100_read_reg_uartout(uint8_t addr)
{
	uint8_t reg;

	reg = cc1100_read_reg(addr);

	#if 1

	puthex(addr);
	putc(0x5c);
	puthex(reg);
	putc(0x0d);
	putc(0x0a);

	#endif

	return reg;
}




#if 1

void cc1101_init02(void)
{


	#if 0
	cc1100_cfg_append_status(CC1100_APPEND_STATUS_ENABLE);
	cc1100_cfg_crc_autoflush(CC1100_CRC_AUTOFLUSH_DISABLE);
	cc1100_cfg_white_data(CC1100_DATA_WHITENING_ENABLE);
	cc1100_cfg_crc_en(CC1100_CRC_CALCULATION_ENABLE);
	cc1100_cfg_freq_if(0x0C);
	cc1100_cfg_fs_autocal(CC1100_AUTOCAL_NEVER);
	cc1100_cfg_mod_format(CC1100_MODULATION_GFSK);
    //cc1100_cfg_mod_format(CC1100_MODULATION_MSK);
	cc1100_cfg_sync_mode(CC1100_SYNCMODE_30_32);
	cc1100_cfg_manchester_en(CC1100_MANCHESTER_DISABLE);
	#endif






	#if 1		//carrier frequency output
    cc1100_cfg_append_status(CC1100_APPEND_STATUS_ENABLE);
    cc1100_cfg_crc_autoflush(CC1100_CRC_AUTOFLUSH_DISABLE);
    cc1100_cfg_white_data(CC1100_DATA_WHITENING_ENABLE);
    cc1100_cfg_crc_en(CC1100_CRC_CALCULATION_ENABLE);
    cc1100_cfg_freq_if(0x0C);
    cc1100_cfg_fs_autocal(CC1100_AUTOCAL_NEVER);
 

	//CC1100_AUTOCAL_IDLE_TO_TX_RX 
    cc1100_cfg_mod_format(CC1100_MODULATION_GFSK);


	/*carria freq check*/
    //cc1100_cfg_mod_format(CC1100_MODULATION_ASK);
	cc1100_cfg_sync_mode(CC1100_SYNCMODE_NO_PREAMB);
	//cc1100_write_reg(CC1100_REG_FREND0,(cc1100_read_reg(CC1100_REG_FREND0) | 0x01));
  	//cc1100_cfg_fs_autocal(CC1100_AUTOCAL_IDLE_TO_TX_RX);
    //cc1100_cfg_mod_format(CC1100_MODULATION_MSK);
    cc1100_cfg_sync_mode(CC1100_SYNCMODE_30_32);
    cc1100_cfg_manchester_en(CC1100_MANCHESTER_DISABLE);




	cc1100_write_reg(CC1100_REG_MDMCFG3,0x83);	//DATA rate 9.6kbps
 	//cc1100_write_reg(CC1100_REG_MCSM0,(cc1100_read_reg(CC1100_REG_MCSM0) | 0x01));	//DATA rate 9.6kbps
    //printf("CC1100 initialized\r\n");
	#endif

	#if 1
	cc1100_read_reg_uartout(CC1100_REG_PKTCTRL1);
	cc1100_read_reg_uartout(CC1100_REG_PKTCTRL0);
	cc1100_read_reg_uartout(CC1100_REG_FSCTRL1);
	cc1100_read_reg_uartout(CC1100_REG_MCSM0);
	cc1100_read_reg_uartout(CC1100_REG_MDMCFG2);

	#endif



	#if 1


	cc1100_read_reg_uartout(CC1100_REG_IOCFG2);
	cc1100_read_reg_uartout(CC1100_REG_IOCFG1);
	cc1100_read_reg_uartout(CC1100_REG_IOCFG0);
	cc1100_read_reg_uartout(CC1100_REG_FIFOTHR);
	cc1100_read_reg_uartout(CC1100_REG_SYNC1);
	cc1100_read_reg_uartout(CC1100_REG_SYNC0);
	cc1100_read_reg_uartout(CC1100_REG_PKTLEN);
	cc1100_read_reg_uartout(CC1100_REG_PKTCTRL1);
	cc1100_read_reg_uartout(CC1100_REG_PKTCTRL0);
	cc1100_read_reg_uartout(CC1100_REG_ADDR);
	cc1100_read_reg_uartout(CC1100_REG_CHANNR);
	cc1100_read_reg_uartout(CC1100_REG_FSCTRL1);
	cc1100_read_reg_uartout(CC1100_REG_FSCTRL0);
	cc1100_read_reg_uartout(CC1100_REG_FREQ2);
	cc1100_read_reg_uartout(CC1100_REG_FREQ1);
	cc1100_read_reg_uartout(CC1100_REG_FREQ0);
	cc1100_read_reg_uartout(CC1100_REG_MDMCFG4);
	cc1100_read_reg_uartout(CC1100_REG_MDMCFG3);
	cc1100_read_reg_uartout(CC1100_REG_MDMCFG2);
	cc1100_read_reg_uartout(CC1100_REG_MDMCFG1);
	cc1100_read_reg_uartout(CC1100_REG_MDMCFG0);
	cc1100_read_reg_uartout(CC1100_REG_DEVIATN);
	cc1100_read_reg_uartout(CC1100_REG_MCSM2);
	cc1100_read_reg_uartout(CC1100_REG_MCSM1);
	cc1100_read_reg_uartout(CC1100_REG_MCSM0);
	cc1100_read_reg_uartout(CC1100_REG_FOCCFG);
	cc1100_read_reg_uartout(CC1100_REG_BSCFG);
	cc1100_read_reg_uartout(CC1100_REG_AGCCTRL2);
	cc1100_read_reg_uartout(CC1100_REG_AGCCTRL1);
	cc1100_read_reg_uartout(CC1100_REG_AGCCTRL0);
	cc1100_read_reg_uartout(CC1100_REG_WOREVT1);
	cc1100_read_reg_uartout(CC1100_REG_WOREVT0);
	cc1100_read_reg_uartout(CC1100_REG_WORCTRL);
	cc1100_read_reg_uartout(CC1100_REG_FREND1);
	cc1100_read_reg_uartout(CC1100_REG_FREND0);
	cc1100_read_reg_uartout(CC1100_REG_FSCAL3);
	cc1100_read_reg_uartout(CC1100_REG_FSCAL2);
	cc1100_read_reg_uartout(CC1100_REG_FSCAL1);
	cc1100_read_reg_uartout(CC1100_REG_FSCAL0);
	cc1100_read_reg_uartout(CC1100_REG_RCCTRL1);
	cc1100_read_reg_uartout(CC1100_REG_RCCTRL0);
	cc1100_read_reg_uartout(CC1100_REG_FSTEST);
	cc1100_read_reg_uartout(CC1100_REG_PTEST);
	cc1100_read_reg_uartout(CC1100_REG_AGCTEST);
	cc1100_read_reg_uartout(CC1100_REG_TEST2);
	cc1100_read_reg_uartout(CC1100_REG_TEST1);
	cc1100_read_reg_uartout(CC1100_REG_TEST0);

	#endif


}

#endif





void cc1101_8PATABLE_read_reg(void)
{
	u8 i;
	u8 reg[10];

	spi1_select(SPI1_CC1100);
	spi1_write_single(0x3e | CC1100_ACCESS_READ_BURST);
	for(i=0;i<8;i++)
	{
		reg[i] = spi1_read_single();
	}
	spi1_deselect(SPI1_CC1100);


	for(i=0;i<8;i++)
	{
		putc(0x54);
		puthex(i);
		putc(0x5c);
		puthex(reg[i]);
		putc(0x0d);
		putc(0x0a);
	}



}



void cc1101_8PATABLE_write_reg(u8 * reg)
{
	u8 i;


	spi1_select(SPI1_CC1100);
	spi1_write_single(0x3e | CC1100_ACCESS_WRITE_BURST);
	for(i=0;i<8;i++)
	{
		spi1_write_single(reg[i]);
	}
	spi1_deselect(SPI1_CC1100);

}




void spi_signalpin_opendrain_active(void)
{
	SPCR &= ~(1<<SPE);	//SPI non active
	//DDRB &= ~(1<<PB0);	//B_CTL
	DDRB &= ~(1<<PB2);	//CSn
	DDRB &= ~(1<<PB3);	//MOSI
	DDRB &= ~(1<<PB5);	//SCK

	PORTB &= ~(1<<PB2);	//CSn

	//PORTC &= ~(1<<PC0);
	//PORTC &= ~(1<<PC1);
	PORTC = 0x00;
	PORTD = 0x00;
}


void spi_signalpin_opendrain_nonactive(void)
{

	spi1_init();		
	//DDRB |= (1<<PB0);	//B_CTL
	PORTB &= ~(1<<PB2);	//CSn
	DDRB |= (1<<PB2);	//CSn output

	PORTC |= (1<<PC0);
	PORTC |= (1<<PC1);
	PORTC = 0x00;
	PORTD = 0xf3;

}






void alert_data_get(cc1101_tx_data * tx_data)
{

	tx_data->serial[0] = 0x4D;	//M
	tx_data->serial[1] = 0x37;	//E
	tx_data->serial[2] = 0x34;	//T
	tx_data->serial[3] = 0x00;	//0
	tx_data->serial[4] = 0x00;	//0
	tx_data->serial[5] = 0x00;	//0


	tx_data->data01 = 1;	//EMG_SIG data
	tx_data->data02 = 2;	//test_sig_timer_data
	tx_data->data03 = 3;	//BATT_data
	tx_data->data04 = 4;	//RSSI_data


}



u8 get_input_data(void)
{
	u8 reg = 0;

	reg = (reg & 0xFF) | (((PIND) << 2) & 0x80);	//F_SEL2
	reg = (reg & 0xFF) | (((PIND) << 2) & 0x40);	//F_SEL1

	reg = (reg & 0xFF) | (((PIND) >> 2) & 0x20);	//D_SEL2
	reg = (reg & 0xFF) | (((PIND) >> 2) & 0x10);	//D_SEL1

	reg = (reg & 0xFF) | (((PINC) << 2) & 0x08);	//M_SEL2
	reg = (reg & 0xFF) | (((PINC) << 2) & 0x04);	//M_SEL1


	return reg;
}


#if 1

void tx_fifo_set(cc1101_tx_data *tx_data)
{
	u8 i;
	uint8_t tx_buffer[100];
	uint8_t tx_length = 0;


	for(i=0;i<70;i++)
	{
		//tx_buffer[i] = tx_data->serial[i];
		tx_buffer[i] = i;
	}

	tx_buffer[i++] = tx_data->data01;
	tx_buffer[i++] = tx_data->data02;
	tx_buffer[i++] = tx_data->data03;
	tx_buffer[i++] = tx_data->data04;

	tx_length = i;


	cc1100_cmd_idle();
	cc1100_cmd_flush_tx();
	#if 1
	cc1100_read_reg_uartout((CC1100_REG_TXBYTES | CC1100_ACCESS_STATUS));
	cc1100_read_reg_uartout((CC1100_REG_MARCSTATE | CC1100_ACCESS_STATUS));
	#endif
	cc1100_cmd_calibrate();
	//cc1100_cfg_gdo0(CC1100_GDOx_SYNC_WORD);
	cc1100_cfg_gdo0(CC1100_GDOx_CHIP_RDY);

	//cc1100_gdo0_int_set_falling_edge();
	mdelay(2);
	cc1100_gdo0_int_clear();
	cc1100_gdo0_int_enable();
	//cc1100_gdo0_register_callback(vEndOfTx_cb);
	mdelay(2);
	cc1100_gdo2_int_disable();
	cc1100_fifo_put((&tx_length), 1);
	cc1100_fifo_put(tx_buffer, tx_length);




	#if 1
	cc1100_read_reg_uartout((CC1100_REG_TXBYTES | CC1100_ACCESS_STATUS));
	#endif

}

#endif


//u8 baud = 0;






void cc1101_carrier_waveoutput_setup(u8 input_data,u8 * pt_data)
{
	u8 f_reg[3] = {0,0,0};
	u8 temp;


	if((input_data & 0xC0)==0xC0)			//426.3625MHz(Ch5) nearly 426.362152
	{
		f_reg[2] = 0x10;
		f_reg[1] = 0x66;
		f_reg[0] = 0x07;
	
	}else if((input_data & 0xC0)==0x80){	//426.4625MHz(Ch9) nearly 426.462128
		f_reg[2] = 0x10;
		f_reg[1] = 0x67;
		f_reg[0] = 0x03;

	}else if((input_data & 0xC0)==0x40){	//426.5625MHz(Ch13)
		f_reg[2] = 0x10;
		f_reg[1] = 0x68;
		f_reg[0] = 0x00;

	}else if((input_data & 0xC0)==0x00){	//426.6625MHz(Ch17)	nearly 426.662476
		f_reg[2] = 0x10;
		f_reg[1] = 0x68;
		f_reg[0] = 0xFC;

	}


	temp = f_reg[0];

	if((eeprom_read_byte(0x01)==0x80))
	{
		f_reg[0] = f_reg[0]-eeprom_read_byte(0x00);
		if(f_reg[0] > temp)
			f_reg[1] -= 1;
	}
	else{
		f_reg[0] = f_reg[0]+eeprom_read_byte(0x00);
		if(f_reg[0] < temp)
			f_reg[1] += 1;
	}




	cc1100_write_reg(CC1100_REG_FREQ2, f_reg[2]);
	cc1100_write_reg(CC1100_REG_FREQ1, f_reg[1]);
	cc1100_write_reg(CC1100_REG_FREQ0, f_reg[0]);


	#if 0
    cc1100_cfg_append_status(CC1100_APPEND_STATUS_ENABLE);
    cc1100_cfg_crc_autoflush(CC1100_CRC_AUTOFLUSH_DISABLE);
    cc1100_cfg_white_data(CC1100_DATA_WHITENING_ENABLE);
    cc1100_cfg_crc_en(CC1100_CRC_CALCULATION_ENABLE);
    cc1100_cfg_freq_if(0x0C);
    cc1100_cfg_fs_autocal(CC1100_AUTOCAL_NEVER);
	#endif


	/*carria freq check*/
	cc1100_cfg_sync_mode(CC1100_SYNCMODE_NO_PREAMB);
    cc1100_cfg_sync_mode(CC1100_SYNCMODE_30_32);
    cc1100_cfg_manchester_en(CC1100_MANCHESTER_DISABLE);

	cc1100_write_reg(CC1100_REG_MDMCFG3,0x83);	

	cc1101_8PATABLE_write_reg(pt_data);
	cc1100_cfg_mod_format(CC1100_MODULATION_ASK);

	//fosc chech
	cc1100_write_reg(CC1100_REG_IOCFG2, CC1100_GDOx_CLK_XOSC_1);
}



void init_voltcomparator(void)
{
	//ACSR |= 1<<ACD;
	//mdelay(1000);
	ACSR = 0x4b;
	DIDR1 = 0x02;
}






u8 add_batt_low(void)
{
	u8 temp_data;

	#if 0
	u8 add_data;
	u8 temp_data;

	temp_data = (ACSR & 0x10);
	temp_data = (temp_data << 3);
	ACSR |= 1<<ACI;
	
	add_data = data + temp_data;
	return add_data;
	#endif

	B_CTL_HIGH;

	init_ad();
	ADCSRA |= _BV(ADSC);					//変換開始 要ﾙｰﾌﾟ内
	while((ADCSRA&0x10)==0x00);

	ADCSRA |= (1<<ADIF);					//ADIF clear

	temp_data = ADCH;

	//a = ( ADC >> 4 );						//AD変換結果 4bitｼﾌﾄ= 6bit:0-64
	ad_diseable();
	B_CTL_LOW;

	puthex(a);
	puthex(0x5C);
	puthex(b);
	putc(0x0d);
	putc(0x0a);
	putc(0x0d);
	putc(0x0a);

	return temp_data;
}




void init_ad(void)
{
	ADCSRA = 0b10000100; // AD許可:1 AD開始:0 AD自動起動:0 AD割込:0 AD完了割込:0 ck/16
    ADMUX = 0xE7;       //AREF外部電圧、入力PC0

}


void ad_diseable(void)
{
	ADCSRA = 0b00000100; // AD許可:0 AD開始:0 AD自動起動:0 AD割込:0 AD完了割込:0 ck/16
    //ADMUX = 0x00;       //AREF外部電圧、入力PC0

}




// エラー
void i2c_error(void)
{
    //putch('['); puthex2(TWSR); putch(']'); // TWSRの内容
    //putch(0x0d); putch(0x0a); // 改行
    //PORTB = 0x01; // LED点灯
    while(1) ;
}

// 通信速度の初期化
void i2c_init(void)
{
    TWSR = 0b00000000;  // 1分周
    TWBR = 32;          // 100k = 8MHz / (16 + 2 * TWBR * 1)
}



// master 1byte送信
void i2c_write(u8 d)
{
    TWDR = d; // 送信データ
    TWCR = _BV(TWINT) | _BV(TWEN);
    while( !(TWCR & _BV(TWINT)) ) ; // データの送出完了待機
    if((TWSR & TW_STATUS_MASK) != TW_MT_DATA_ACK) i2c_error();
}

// master 1byte受信(ackを返す)
u8 i2c_read_ack(void)
{
    TWCR = _BV(TWINT) | _BV(TWEN) | _BV(TWEA);
    while( !(TWCR & _BV(TWINT)) ) ; // 受信完了待ち
    if((TWSR & TW_STATUS_MASK) != TW_MR_DATA_ACK) i2c_error();
    return TWDR; // データを返す
}

// master 1byte受信(noackを返す)
u8 i2c_read_nak(void)
{
    TWCR = _BV(TWINT) | _BV(TWEN);
    while( !(TWCR & _BV(TWINT)) ) ; // 受信完了待ち
    if((TWSR & TW_STATUS_MASK) != TW_MR_DATA_NACK) i2c_error();
    return TWDR; // データを返す
}

// master送信開始、IDはslave address ＜＜ 1
void i2c_start(u8 id)
{
    u8 s;

    // 開始条件を送る
    TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN);
    while( !(TWCR & _BV(TWINT)) ) ; // 開始条件の送出完了待機
    s = TWSR & TW_STATUS_MASK;
    if(s != TW_START && s != TW_REP_START) i2c_error();

    // アドレスを送る
    TWDR = id;
    TWCR = _BV(TWINT) | _BV(TWEN);
    while( !(TWCR & _BV(TWINT)) ) ; // アドレスの送出完了待機
    s = TWSR & TW_STATUS_MASK;
    if(s != TW_MT_SLA_ACK && s != TW_MR_SLA_ACK) i2c_error();
}

// master送信終了
void i2c_stop(void)
{
    TWCR = _BV(TWINT) | _BV(TWSTO) | _BV(TWEN);
    while( !(TWCR & _BV(TWSTO)) ) ;
    // statusはTW_NO_INFOになる
}


#define RTC_R2223L (0x32 << 1)    // RICOH RTC R2223L/Tのslave address


void rtc_1byte_data_write(u8 addr,u8 data)
{
	/*write*/
	i2c_start(RTC_R2223L | TW_WRITE);
	i2c_write((addr<<4)&0xf0); // register 4
	i2c_write(data); // 14bit resolution
	i2c_stop();
}


u8 rtc_1byte_data_read(u8 addr)
{
	u8 data;

	i2c_start(RTC_R2223L | TW_WRITE);
	i2c_write((addr << 4)&0xF0); // register 0
	i2c_start(RTC_R2223L | TW_READ);
	data = i2c_read_nak(); // 下位読み込み(最後はNAKを返す)
	i2c_stop();
	return data;
}


void rtc_3byte_data_read(u8 start_addr,u8 * data)
{
	i2c_start(RTC_R2223L | TW_WRITE);
	i2c_write((start_addr << 4)&0xF0); // register 0
	i2c_start(RTC_R2223L | TW_READ);
	data[0] = i2c_read_ack(); // 上位読み込み
	data[1] = i2c_read_ack(); // 上位読み込み
	data[2] = i2c_read_nak(); // 下位読み込み(最後はNAKを返す)
	i2c_stop();
}




ISR(USART_RX_vect)
{
	test_cnt02++;
	test_cnt02=UDR0;
	puthex(test_cnt02);
	mdelay(100);
	//puthex(0x55);
	//putc(0x47);
	//putc(0x4a);
}




ISR(INT0_vect)
{
	test_cnt02++;
	puthex(0x33);
	mdelay(100);

}

	//u8 pt_data[] = {0xC5,0xC0,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7};		\\10dB
	//u8 pt_data[] = {0xC5,0x60,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7};		//0dB
	//u8 pt_data[] = {0xC5,0xC5,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7};
	u8 pt_data[] = {0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00};		//10dB
	//u8 pt_data[] = {0x60,0x60,0x00,0x00,0x00,0x00,0x00,0x00};		//0dB
	//u8 pt_data[] = {0x60,0x60,0x00,0x00,0x00,0x00,0x00,0x00};		//0dB
	//u8 pt_data[] = {0x34,0x34,0x00,0x00,0x00,0x00,0x00,0x00};		//-10dB

ISR(INT1_vect)
{
	u8 i;
	//u8 a;
	//u8 b;
	//register u8 input_data=0;
	u8 new_input_data=0;
	//volatile unsigned char chk_state=0;

	test_cnt02++;
	puthex(0x44);
	mdelay(100);



	//DDRB |= (1<<PB0);	//B_CTL
	spi_signalpin_opendrain_nonactive();


    cc1100_init();
	cc1101_init02();



	i2c_init();

	
	rtc_1byte_data_write(0x00,0x04);
	rtc_1byte_data_write(0x01,0x03);
	rtc_1byte_data_write(0x02,0x02);


	test_temp = rtc_1byte_data_read(0x00);
	test_temp2 = rtc_1byte_data_read(0x01);
	test_temp3 = rtc_1byte_data_read(0x02);

	//while(1);




	#if 0

	while(1)
	{
		b = add_batt_low();
	}


	#endif


	b = add_batt_low();




	#if 1
	status = KEY_CHK;

	while(1)
	{
		switch(status)
		{
			default:
				break;
			case KEY_CHK:

				input_data = ~get_input_data();


				if((input_data&0x04)==0x04)
					status = CA_OUT_SETUP;
				else
					status = DATA_OUT_SETUP;
				break;
			case CA_OUT_SETUP:
				cc1101_carrier_waveoutput_setup(input_data,pt_data);
				status = CA_WAVEOUT;
				cc1100_read_reg_uartout(CC1100_REG_FREQ2);
				cc1100_read_reg_uartout(CC1100_REG_FREQ1);
				cc1100_read_reg_uartout(CC1100_REG_FREQ0);
				//mdelay(1);
				status = CA_WAVEOUT;
				break;
			case CA_WAVEOUT:
				//cc1100_cmd_flush_tx();
				alert_data_get(&tx_data);
				tx_fifo_set(&tx_data);
				cc1100_cmd_tx();
				if(cc1100_read_reg(CC1100_REG_MARCSTATE | CC1100_ACCESS_STATUS)==0x01)
				{
					cc1100_cmd_flush_tx();
					cc1100_cmd_tx();
				}
				status = CA_KEY_CHANGE_CHK;
				break;
			case DATA_OUT_SETUP:
			case FIFO_SETUP:
			case DATA_WAVEOUT:
				status = KEY_CHK;
				break;
			case CA_KEY_CHANGE_CHK:
				new_input_data = ~get_input_data();
				if(new_input_data != input_data)
					status = KEY_CHK;
				break;					
		}

	}
	#endif




	#if 1
	B_CTL_HIGH;
	sdelay(1);
	B_CTL_LOW;
	#endif






	#if 0

	for(i=0;i<1;i++)
	{
	B_CTL_HIGH;
	sdelay(1);
	B_CTL_LOW;
	sdelay(1);
	}


	sdelay(3);


	for(i=0;i<10;i++)
	{
	B_CTL_HIGH;
	mdelay(100);
	B_CTL_LOW;
	sdelay(1);
	}

    cc1100_init();
	cc1101_init02();


	input_data = ~get_input_data();





	if((input_data&0x80)==0x80)
	{
		cc1100_cmd_flush_tx();
		cc1100_cmd_pwd();
	}

	if((input_data&0x40)==0x40)
	{
		//cc1100_cmd_pwd();
		DDRB &= ~(1<<PB0);	//B_CTL
	}
	

	#endif


	cc1100_cmd_idle();
	cc1100_cmd_pwd();

	spi_signalpin_opendrain_active();

	
}











int main()
{
	#if 1

	hw_setup();
	//init_voltcomparator();
	//init_ad();
	inituart();
	#endif


	CS_CC1101_HIGH;

	B_CTL_LOW;
	mdelay(100);


	#if 1
    cc1100_init();
	cc1101_init02();
	#endif

	#if 0
	cc1100_read_reg_uartout(CC1100_PATABLE_ADDR);
	cc1101_8PATABLE_read_reg();

	#endif


	#if 1
	test1 = cc1100_read_reg_uartout(CC1100_REG_FREQ2);
	test2 = cc1100_read_reg_uartout(CC1100_REG_FREQ1);
	test3 = cc1100_read_reg_uartout(CC1100_REG_FREQ0);
	#endif

	#if 1
	status = STARTUP;
	test_cnt02 = 0;
	//set_sleep_mode(SLEEP_MODE_PWR_DOWN);
	set_sleep_mode(SLEEP_MODE_PWR_SAVE);


	#endif


	sei();


	#if 0
	eeprom_busy_wait(); 
	eeprom_write_byte(0x00,0x89);
	eeprom_write_byte(0x00,0x7F);
	eeprom_busy_wait(); 
	eeprom_write_byte(0x01,0x66);

	#endif

	//cc1100_cmd_flush_tx();
	cc1100_cmd_idle();
	cc1100_cmd_pwd();


	spi_signalpin_opendrain_active();

	/* Enter the infinite loop */
    while (1)
    {

		#if 1
		sleep_mode();
		#endif


	}
}


