I2C 模擬讀寫程式碼
阿新 • • 發佈:2018-12-17
static void Delay1us(void)//please revise this function according to your system { u8 i; for(i=0;i<15;i++); } void I2C_init(void) { // SDA CLK初始化 GPIOE->DDR|=((1<<I2C_SCK)); // I2C_SDA I2C_SCK output GPIOE->CR1|= ((1<<I2C_SCK)); // I2C_SDA I2C_SCK output推輓輸出 GPIOE->CR2&= ~((1<<I2C_SCK)); // Toggle GPIO PIN PB 無中斷 GPIOE->ODR|=(1<<I2C_SCK); // I2C_SDA I2C_SCK=1 GPIOE->DDR|=((1<<I2C_SDA)); // I2C_SDA I2C_SCK output GPIOE->CR1|= ((1<<I2C_SDA)); // I2C_SDA I2C_SCK output推輓輸出 GPIOE->CR2&= ~((1<<I2C_SDA)); // Toggle GPIO PIN PB 無中斷 GPIOE->ODR|=(1<<I2C_SDA); } void I2C_Start(void) { I2C_DATA_HIGH; Delay1us(); I2C_CLK_HIGH; Delay1us(); I2C_DATA_LOW; Delay1us(); I2C_CLK_LOW; Delay1us(); } void I2C_Stop(void) { I2C_CLK_LOW; Delay1us(); I2C_DATA_LOW; Delay1us(); I2C_CLK_HIGH; Delay1us(); I2C_DATA_HIGH; Delay1us(); } void I2C_ack(void) { I2C_SDA_DIROUT; GPIOE->CR1|= (1<<I2C_SDA); I2C_CLK_LOW; I2C_DATA_LOW; Delay1us(); I2C_CLK_HIGH; Delay1us(); I2C_CLK_LOW; } void I2C_nack(void) { I2C_SDA_DIROUT; GPIOE->CR1|= (1<<I2C_SDA); I2C_CLK_LOW; I2C_DATA_HIGH; Delay1us(); I2C_CLK_HIGH; Delay1us(); I2C_CLK_LOW; } u8 I2C_ReceiveACK(void) { u8 ackflag; I2C_SDA_DIRIN; GPIOE->CR1&= ~(1<<I2C_SDA); Delay1us(); I2C_CLK_HIGH; Delay1us(); ackflag = (u8)I2C_DATA_READ; I2C_CLK_LOW; I2C_SDA_DIROUT; GPIOE->CR1|= (1<<I2C_SDA); Delay1us(); return ackflag; } void I2C_sendbyte(u8 I2CSendData) { u8 i; Delay1us(); I2C_CLK_LOW; for(i = 0;i < 8;i++) { if(I2CSendData & 0x80)I2C_DATA_HIGH; //if high bit is 1,SDA= 1 else I2C_DATA_LOW; //else SDA=0 Delay1us(); I2C_CLK_HIGH; Delay1us(); I2CSendData <<= 1; //shift left 1 bit I2C_CLK_LOW; } } u8 I2c_Readbyte(void) { u8 i; u8 ucRDData = 0; //return value I2C_SDA_DIRIN; GPIOE->CR1&= ~(1<<I2C_SDA); Delay1us();; for(i = 0;i < 8;i++) { I2C_CLK_HIGH; ucRDData <<= 1; Delay1us(); if(I2C_DATA_READ) { //beep(BEEP_KEY); ucRDData|=0x01; } I2C_CLK_LOW; Delay1us(); } return(ucRDData); } void I2c_Read(u8 adr,u8 *pBuf,u8 CMD) { u8 buff; I2C_Start(); I2C_sendbyte(adr); buff=I2C_ReceiveACK(); if(buff!=0) { tiic=1; return; } else tiic=0; I2C_sendbyte(CMD); buff=I2C_ReceiveACK(); if(buff!=0) { tiic=2; return; } I2C_Start(); I2C_sendbyte(adr+1); buff=I2C_ReceiveACK(); if(buff!=0) { tiic=3; return; } *pBuf = I2c_Readbyte(); I2C_ack(); *pBuf = I2c_Readbyte(); tiic=*pBuf; I2C_nack(); I2C_Stop(); } void I2c_Write(u8 adr,u8* pBuf,u8 CMD) { I2C_Start(); I2C_sendbyte(adr); I2C_ReceiveACK(); I2C_sendbyte(CMD); I2C_ReceiveACK(); I2C_sendbyte(*pBuf); I2C_ReceiveACK(); I2C_Stop(); } I2c_Read(0x80,&key80,0x08); //p mKEY.key_input|=key80;