论坛元老
 
- 积分
- 6662
- 金钱
- 6662
- 注册时间
- 2016-5-29
- 在线时间
- 910 小时
|
发表于 2017-12-15 16:33:47
|
显示全部楼层
本帖最后由 操作系统 于 2017-12-15 16:35 编辑
判断有没有应答不用WHILE循环.直接读取就可以了.有ACK..很快就会有ACK信号.要是没有的话.你等一万年也不会有.
#include "main.h"
#include "i2c.h"
#include "delay.h"
#include "wth040.h"
#include "sweep_key.h"
#include "softTimer.h"
#define CLK_B 6
#define SDA_B 7
#define SCL_0() GPIOB->BRR =(1<<CLK_B)
#define SCL_1() GPIOB->BSRR =(1<<CLK_B)
#define read_scl() (GPIOB->IDR&(1<<CLK_B))
#define SDA_0() GPIOB->BRR =(1<<SDA_B)
#define SDA_1() GPIOB->BSRR = (1<<SDA_B)
#define read_sda() (GPIOB->IDR&(1<<SDA_B))
#define SDA_DIR1() SDA_1()
#define delayUs() delayUs(4)
static void start(void);
static void stop(void);
static uc send_byte(uc a); //发一个字节
static uc recive_byte(uc ans); //接收一个字节
void i2c_init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = (1 << CLK_B) | (1 << SDA_B);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOB,&GPIO_InitStructure);
GPIOB->BSRR = (1 << CLK_B) | (1 << SDA_B);
}
static void start(void) //开始信号
{
SDA_1();
SCL_1();
delayUs();
delayUs();
SDA_0();
delayUs();
delayUs();
SCL_0();
delayUs();
}
static void stop(void) //停止信号
{
SDA_0();
delayUs();
delayUs();
SCL_1();
delayUs();
delayUs();
SDA_1();
}
static uc send_byte(uc a) //发送一个字节,高位先发.
{
uc i;
i = 8;
while (i--)
{
if (0x80 & a) SDA_1();
else SDA_0();
delayUs();
SCL_1();
while (read_scl() == 0)
{
;
}
delayUs();
SCL_0();
a <<= 1;
delayUs();
}
SDA_DIR1();
delayUs();
SCL_1();
delayUs();
i = read_sda();
SCL_0();
delayUs();
delayUs();
return i;
}
static uc recive_byte(uc ans)
{
uc ret,i;
ret = 0;
i = 8;
SDA_DIR1();
while (i--)
{
ret <<= 1;
SCL_1();
while (read_scl() == 0)
{
;
}
delayUs();
if (read_sda()) ret++;
SCL_0();
delayUs();
}
if (ans != 0)
{
SDA_0();
}
else
{
SDA_1();
}
delayUs();
SCL_1();
delayUs();
SCL_0();
delayUs(); //这个延时很重要.没有这个延时,读取下一次字节时的第一位有可能会丢失.
delayUs();
//delayUs();
return ret;
}
ui i2c_wr_buf(uc device,uc addr,uc * buf,ui len)
{
start();
if (send_byte(device) != 0) goto er;
if (send_byte(addr) != 0) goto er;
while (len)
{
len--;
if (send_byte(*buf++) != 0) goto er;
}
stop();
return 0;
er:
stop();
return 1;
}
ui i2cWriteWord(uc device,uc addr,ui buf)
{
start();
if (send_byte(device) != 0) goto er;
if (send_byte(addr) != 0) goto er;
if (send_byte(buf&0xff) != 0) goto er;
if (send_byte(buf>>8) != 0) goto er;
stop();
return 0;
er:
stop();
return 1;
}
ui i2c_read_buf(uc device,uc addr,uc * buf,ui len)
{
start();
if (send_byte(device) != 0) goto er;
if (send_byte(addr) != 0) goto er;
start();
if (send_byte(device | 1) != 0) goto er;
while (len--) *buf++ = recive_byte(len > 0);
stop();
return 1;
er:
stop();
return 0;
}
ui i2cRead(uc device,uc * buf,ui len)
{
start();
if (send_byte(device | 1) != 0) goto er;
while (len--) *buf++ = recive_byte(len > 0);
stop();
return 1;
er:
stop();
return 0;
}
|
|