STM8S003F3P6单片机 使用硬件I2C,程序经常死机,偶尔才正常,一直死在I2C_CheckEvent 函数里面, 弄得好心累,求大神解救 程序如下: #define I2C_Speed 100000 #define I2C1_SLAVE_ADDRESS7 0xA0 GPIO_Init(GPIOB, GPIO_PIN_4, GPIO_MODE_OUT_OD_HIZ_FAST);//PB4 I2C_SCL 功能引脚,总线的时钟脚,设为高速开漏高阻输出。 GPIO_Init(GPIOB, GPIO_PIN_5, GPIO_MODE_OUT_OD_HIZ_FAST);//PB5 I2C_SDA 功能引脚,总线的数据脚,设为高速开漏高阻输出 /********************************************* I2C总线写一个字节 **********************************************/ void I2C_Write(unsigned char ADDR,unsigned char Wdata) { ITStatus it_status; FlagStatus flag_status; I2C_GenerateSTART(ENABLE); //I2C启动 /* Send STRAT condition */ /* Test on EV5 and clear it */ //while(!I2C_CheckEvent(I2C_EVENT_MASTER_START_SENT)); while(!I2C_CheckEvent(I2C_EVENT_MASTER_MODE_SELECT )); I2C_Send7bitAddress(ADDR, I2C_DIRECTION_TX); //写I2C从器件地址和写方式 /* Test on EV6 and clear it */ //while(!I2C_CheckEvent(I2C_EVENT_MASTER_ADDRESS_ACKED)); while(!I2C_CheckEvent(I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)); I2C_SendData(Wdata); //写数据到器件相应寄存器 /* Test on EV8 and clear it */ while (!I2C_CheckEvent(I2C_EVENT_MASTER_BYTE_TRANSMITTING)); /* Send STOP condition */ I2C_GenerateSTOP(ENABLE); } /********************************************* I2C总线读一个字节 返回:16位数值 **********************************************/ unsigned int I2C_Read(unsigned char ADDR) { unsigned int temp; unsigned char tmp1,tmp2; /* While the bus is busy */ while(I2C_GetFlagStatus(I2C_FLAG_BUSBUSY)); I2C_GenerateSTART(ENABLE); //I2C启动 /* Generate start & wait event detection */ /* Test on EV5 and clear it */ //while (!I2C_CheckEvent(I2C_EVENT_MASTER_START_SENT)); while (!I2C_CheckEvent(I2C_EVENT_MASTER_MODE_SELECT)); I2C_Send7bitAddress(ADDR, I2C_DIRECTION_RX); //写I2C从器件地址和写方式 /* Test on EV6 and clear it */ //while (!I2C_CheckEvent(I2C_EVENT_MASTER_ADDRESS_ACKED)); while (!I2C_CheckEvent(I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED)); //I2C_ClearFlag(I2C_FLAG_ADDRESSSENTMATCHED); /* 2 variables are used to avoid any compiler optimization */ /* Read the SR1 register */ tmp1 = I2C->SR1; /* Read the SR3 register */ tmp2 = I2C->SR3; while (!I2C_CheckEvent(I2C_EVENT_MASTER_BYTE_RECEIVED)); temp = I2C_ReceiveData();//启动主I2C读方式 //读取I2C接收数据 第一字节 /* Disable Acknowledgement */ I2C_AcknowledgeConfig(I2C_ACK_NONE); while (!I2C_CheckEvent(I2C_EVENT_MASTER_BYTE_RECEIVED)); temp = (temp<<8)+I2C_ReceiveData(); //读第二字节 合成16位数值 I2C_GenerateSTOP(ENABLE); //I2C停止 I2C_AcknowledgeConfig(I2C_ACK_CURR); //启动主I2C读方式,结果应答NO_ACK return temp; } |
:):):) |
解决了,及时清除标志位,然后加个超时保护就可以很稳定了。 |