本帖最后由 Some_Boy 于 2020-6-15 18:33 编辑
原来使用stm32f103 用模拟IIC 读取BMP180 数据 正常 。现在转换到 HC32F003 上面数据 读不出来!
各位大神帮帮看看!
有问题的:
stm32 读取的 这是好的:
下面是代码:
void BMP_IIC_Init(void)
{
M0P_CLOCK->PERI_CLKEN_f.GPIO = 1;
M0P_GPIO->P25_SEL =0x000; //普通IO
M0P_GPIO->P26_SEL =0x000;
M0P_GPIO->P2DIR_f.P25 =0;
M0P_GPIO->P2DIR_f.P26 =0;
M0P_GPIO->P2PU_f.P25 =1;
M0P_GPIO->P2PU_f.P26 =1;
M0P_GPIO->P2OD_f.P25 =1;//P25 开漏输出
M0P_GPIO->P2OD_f.P26 =1;//P26 开漏输出
M0P_GPIO->P2DR = 0x00; //驱动能力高
M0P_GPIO->P2DR_f.P25 = 0;
M0P_GPIO->P2DR_f.P26 = 0;
Gpio_SetIO(2,5,1);
Gpio_SetIO(2,6,1);
}
void IIC_Init(void)
{
BMP180SCL_H; //SCL = 1;
delay_us(5);
BMP180SDA_H; //SDA = 1;
delay_us(5);
}
void IIC_Start(void)
{
BMP180SDA_H; //SDA = 1;
BMP180SCL_H; //SCL = 1;
delay_us(5);
BMP180SDA_L; //SDA = 0;
delay_us(5);
BMP180SCL_L; //SCL = 0;
}
void IIC_Stop(void)
{
BMP180SDA_L; //SDA = 0;
BMP180SCL_L; //SCL = 0;
delay_us(5);
BMP180SCL_H; //SDA = 1;
BMP180SDA_H; //SCL = 1;
delay_us(5);
}
unsigned char IIC_ReceiveACK(void)
{
unsigned char ACKErr=0;
BMP180SDA_H; //SDA=1;//要读低电平需先拉高再读,否则读到的是错误数据,很重要!
delay_us(5);
BMP180SCL_H; //SCL=1;
delay_us(5);
while(BMP180SDA_read==1) //SDA为高
{
ACKErr++;
if(ACKErr>250)
{
IIC_Stop();
return 1;
}
}
BMP180SCL_L; //SCL=0;
return 0;
}
void IIC_SendACK(unsigned char ack)
{
BMP180SCL_L; //SCL = 0;
if (ack == 1)
BMP180SDA_H;
else if (ack == 0) //应答
BMP180SDA_L;
delay_us(5);
BMP180SCL_H; //SCL = 1;
delay_us(5);
BMP180SCL_L; //SCL = 0;
}
unsigned char IIC_SendByte(unsigned char dat)
{
unsigned char i;
unsigned char bResult=1;
BMP180SCL_L; //SCL = 0;//拉低时钟线
for( i=0;i<8;i++ ) //一个SCK,把dat一位一位的移送到SDA上
{
if( (dat<<i)&0x80 )BMP180SDA_H; //SDA = 1;//先发高位
else BMP180SDA_L; //SDA = 0;
delay_us(5);
BMP180SCL_H; //SCL = 1;
delay_us(5);
BMP180SCL_L; //SCL = 0;
delay_us(5);
}
bResult=IIC_ReceiveACK(); //发送完一个字节的数据,等待接受应答信号
return bResult; //返回应答信号
}
unsigned char IIC_ReadByte(void)
{
unsigned char dat;
unsigned char i;
for( i=0;i<8;i++ )
{
BMP180SCL_L; //SCL = 0;
delay_us(5);
BMP180SCL_H; //SCL = 1;
dat <<= 1;
if(BMP180SDA_read)
dat++;
delay_us(5);
}
return dat;
}
/*从BMP180中读1个字节的数据*/
uint8_t BMP180_ReadOneByte(uint8_t ReadAddr)
{
uint8_t temp = 0;
uint8_t IIC_ComFlag = 1; //IIC通信标志,为0标志正常,1表示通信错误
IIC_Start(); //IIC start
IIC_ComFlag = IIC_SendByte(BMP180_WR_ADDR); //slave address+W:0
printf("IIC_ComFlag=%u \r\n",IIC_ComFlag);
if (IIC_ComFlag == 0) //返回值为0表示通信正常,可以继续通信。否则不通信了
{
IIC_SendByte(ReadAddr); //发送命令代码
IIC_Start();
IIC_SendByte(BMP180_WR_ADDR|0x01); //slave address+R:1
temp = IIC_ReadByte(); //读数据
IIC_SendACK(1);
IIC_Stop();
}
return (temp);
}
|