大家帮我看看这个IIC程序问题在哪里啊 程序运行之后设备地址都写不进去
(我使用的是3.3版的固件库) 急急急!!!
#include "stm32f10x.h"
#include "stm32f10x_i2c.h"
#include "I2C.h"
#include <stdio.h>
#define DETECT_ADDR 0xE8
void I2C_Configuration(void)
{
I2C_InitTypeDef I2C_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
/* PB6,7 SCL and SDA */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD; //设置管脚为复用功能开漏输出
GPIO_Init(GPIOB, &GPIO_InitStructure); //I2C接口使用的GPIO管脚初始化
I2C_DeInit(I2C1);
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C; //设置I2C接口模式
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2; //设置I2C接口的高低电平周期
I2C_InitStructure.I2C_OwnAddress1 = 0x30; //设置I2C接口的主机地址
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable; //设置是否开启ACK响应
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = 100000; //100K速度
I2C_Cmd(I2C1, ENABLE); //使能I2C接口
I2C_Init(I2C1, &I2C_InitStructure); //I2C接口初始化
/*允许1字节1应答模式*/
I2C_AcknowledgeConfig(I2C1, ENABLE); //使能I2C接口响应
}
void I2C_WriteByte(u8 address, u8 addr,u8 dat)
{
/* 起始位 */
I2C_GenerateSTART(I2C1, ENABLE);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT));
/*发送器件地址*/
I2C_Send7bitAddress(I2C1, address, I2C_Direction_Transmitter);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));//程序运行到这里就下不去了
/*发送地址*/
I2C_SendData(I2C1, addr);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
/* 写一个字节命令*/
I2C_SendData(I2C1, dat);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
/* 停止位*/
I2C_GenerateSTOP(I2C1, ENABLE);
}
uint8_t I2C_ReadByte(u8 address, u8 reg)
{
u8 dat;
/* 发送起始位 */
I2C_GenerateSTART(I2C1, ENABLE);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT));/*EV5,主模式*/
/*发送器件地址(写)*/
I2C_Send7bitAddress(I2C1, address, I2C_Direction_Transmitter);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
/*发送地址*/
I2C_SendData(I2C1, reg);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED));/*数据已发送*/
/*起始位*/
I2C_GenerateSTART(I2C1, ENABLE);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT));
/*器件读*/
I2C_Send7bitAddress(I2C1, address+1, I2C_Direction_Receiver);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED));
dat = I2C_ReceiveData(I2C1);
I2C_AcknowledgeConfig(I2C1, DISABLE); //最后一位后要关闭应答的
I2C_GenerateSTOP(I2C1, ENABLE); //发送停止位
return dat;
}
static void Delay(__IO uint32_t nCount)
{
for (; nCount != 0; nCount--);
}
void IIC_Test(void)
{
uint16_t distance;
I2C_WriteByte(DETECT_ADDR ,2, 0xb0); //use command "0xb0" to detect the distance
Delay(80); //安全延时,如果显示不清晰可以将延时调大一些
distance=I2C_ReadByte(DETECT_ADDR , 2);
distance <<= 8;
distance += I2C_ReadByte(DETECT_ADDR , 3);
printf("\n\r %x ",distance);
}
|
|