2019-12-23 18:37发布
gyzzg2030 发表于 2017-9-13 20:43 给楼主一个我们用过的IIC硬件的程序参考 void I2C_Init(void) {
xiepan2010 发表于 2017-9-13 17:26 哪位老司机来个stm8的模拟iic例程看看 怎么改都不行
最多设置5个标签!
非常感谢,不过硬件的用不上
试试老司机的模拟I2C:
#define uchar unsigned char
#define uint unsigned int
#define use_delay_char() uchar delay_char
#define L_go_T_deal(PIN,t) delay_char=t; while( PIN) if((--delay_char)==0)
//枚举 ACK模式选择
typedef enum
{
NAK = 0,
ACK = 1
} ACK_Type;
void MCP3421_IO_init(void)
{
//================SCL pin init===================
SET_GPIO_OUT_PP_HIGH_SLOW(SCL0_PORT,SCL0_NUM);
//================SDA pin init===================
SET_GPIO_OUT_PP_HIGH_SLOW(SDA0_PORT,SDA0_NUM);
}
#if 1
void SomeNOP(void)
{
uchar i = 6;
while(i--);
}
#else
#define SomeNOP() asm("nop")
#endif
void I2C0_Start(void)
{
SET_SDA0_OUT;
SDA0_1;
SCL0_1; SomeNOP();
SDA0_0; SomeNOP();
SCL0_0;
}
void I2C0_Stop(void)
{
SET_SDA0_OUT;
SCL0_0;
SDA0_0; SomeNOP();
SCL0_1; SomeNOP();
SDA0_1;
}
uchar I2C0_Check_ACK(void)
{
use_delay_char();
SET_SDA0_IN;
//SDA0_1;
L_go_T_deal(GET_SDA0, 20) break;
SomeNOP();
SCL0_1; SomeNOP();
SCL0_0; SomeNOP();
SET_SDA0_OUT;
if(delay_char==0) return 0;
else return 1;
}
void I2C0_ACK(void)
{
SET_SDA0_OUT;
SDA0_0;
SomeNOP();
SCL0_1;
SomeNOP();
SCL0_0;
}
void I2C0_NOACK(void)
{
SET_SDA0_OUT;
SDA0_1;
SomeNOP();
SCL0_1;
SomeNOP();
SCL0_0;
}
uchar I2C0_Write_Byte(uchar ch)
{
uchar i = 8;
while(i--)
{
SCL0_0;
if(ch&0x80) SDA0_1;
else SDA0_0;
ch <<= 1; SomeNOP();
SCL0_1; SomeNOP();
}
SCL0_0;
return I2C0_Check_ACK();
}
uchar I2C0_Read_byte(ACK_Type s)
{
unsigned char dat=0,i;
SDA0_1;
SET_SDA0_IN;
for( i=0; i<8; i++ )
{
SomeNOP();
dat <<= 1;
SCL0_1;
if(GET_SDA0) dat++;
SomeNOP();
SCL0_0;
//SomeNOP();
}
SET_SDA0_OUT;
if(s==ACK) I2C0_ACK();
else I2C0_NOACK();
return dat;
}
一周热门 更多>