#include "omw_config.h"
#include "omw_dbg.h"
#include "omw_uart.h"
#include "periph_gpio.h"
#include "periph_iic.h"

void gpio_init(void);
void iic_init(void);
void AT24C16C_page_write(uint8_t page_addr , uint8_t *buf , uint32_t dat_len);
void AT24C16C_continue_read(uint8_t page_addr , uint8_t *buf , uint32_t dat_len);
int main()
{
	int  i = 0, e = 0;
    uint8_t page_write_buf[16],receive_buf[2048];

    omw_dbg_init();
    iic_init();
    gpio_init();
    printf("IIC test ...\n");

    // page write test
    for(i=0;i<16;i++){
		page_write_buf[i] = i;
	}
	for(i=0;i<16;i++){
		
	    AT24C16C_page_write((i<<4), page_write_buf, 16);
	    delay_ms(5);
	}
    // continue read test
	delay_ms(5);
	AT24C16C_continue_read(0,receive_buf,16*16);
	for(i=0;i<256;i++){
		if(receive_buf[i] != (i%16))
		    e++;
	}
	printf("iic page write read test error times:%d",e);
}
void gpio_init(void){
   GPIO_InitTypeDef GPIO_InitStruct;
    // GPIO22_init
    GPIO_StructInit(&GPIO_InitStruct);
    GPIO_InitStruct.GPIO_Pin = GPIO_PIN_22;
    GPIO_InitStruct.GPIO_Mode = GPIO_MODE_IPU;
    GPIO_InitStruct.GPIO_AltFunc = OMW_GPIO22_I2C0_SCL;
    GPIO_InitStruct.GPIO_DriveStrength = GPIO_DRIVE_STRENGTH_3; // highest drive strength
    GPIO_Init(&GPIO_InitStruct);
    //GPIO23_init
    GPIO_StructInit(&GPIO_InitStruct);
    GPIO_InitStruct.GPIO_Pin = GPIO_PIN_23;
    GPIO_InitStruct.GPIO_Mode = GPIO_MODE_IPU;
    GPIO_InitStruct.GPIO_AltFunc = OMW_GPIO23_I2C0_SDA;
    GPIO_InitStruct.GPIO_DriveStrength = GPIO_DRIVE_STRENGTH_3; // highest drive strength
    GPIO_Init(&GPIO_InitStruct); 
}

void iic_init(void){
    IIC_InitTypeDef IIC_InitStruct;
    IIC_StructInit(&IIC_InitStruct);

    int eeprom_addr = 0x50;
	IIC_InitStruct.iic_mode = IIC_MODE_MASTER;                      
	IIC_InitStruct.iic_speed_mode = IIC_SPEED_MODE_FS_PLUS;              //速度模式配置
	IIC_InitStruct.iic_target_addr_mode = IIC_TARGET_ADDR_MODE_7BIT;//主机寻址模式配置，用作slave时不需要配置
	IIC_InitStruct.iic_target_addr = eeprom_addr ;                      //主机地址配置，用作slave时不需要配置 iic使能位置位时不可修改
	IIC_InitStruct.iic_slave_addr_mode = IIC_SLAVE_ADDR_MODE_7BIT;  //从机寻址模式配置，用作master时不需要配置
	IIC_InitStruct.iic_slave_addr = 0;                                  //从机自身地址配置，用作master时不需要配置
	IIC_InitStruct.iic_rx_threshold = 0x07;                             //RX_FIFO水线配置
	IIC_InitStruct.iic_tx_threshold = 0x07;                             //TX_FIFo水线配置

    IIC_Cmd(DISABLE);
    IIC_Init(&IIC_InitStruct);
	IIC_Cmd(ENABLE);
}

void AT24C16C_page_write(uint8_t page_addr , uint8_t *buf , uint32_t dat_len)
{
	IIC_SendByte(page_addr);
	for(int i=0;i<dat_len;i++){
		IIC_SendByte(buf[i]);
	}
	
}

void AT24C16C_continue_read(uint8_t page_addr , uint8_t *buf , uint32_t dat_len)
{
	IIC_SendByte(page_addr);
	IIC_MasterRecv(buf, dat_len);
}