嵌入式-软件模拟I2C通信
使用软件模拟I2C通信,扩展I2C资源
/*********************************************************************************
*
*
* 软件模拟I2C通信的接口
* author:jindouliu2024@163.com
* date:2025.4.10
*
*
* Copyright (c) 2024-2025 jindouliu2024@163.com All right Reserved
* *********************************************************************************/
I2C.c
#include "stm32f10x.h" // Device header
void myi2c_w_scl(uint8_t bitvalue)
{
GPIO_WriteBit(GPIOB,GPIO_Pin_10,(BitAction)bitvalue);
}
void myi2c_w_sda(uint8_t bitvalue)
{
GPIO_WriteBit(GPIOB,GPIO_Pin_11,(BitAction)bitvalue);
}
uint8_t myi2c_r_sda()
{
uint8_t readbit;
readbit=GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_11);
return readbit;
}
void myi2c_Init()
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10|GPIO_Pin_11;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_SetBits(GPIOB,GPIO_Pin_11|GPIO_Pin_10);
}
void myi2c_start()
{
myi2c_w_sda(1);
myi2c_w_scl(1);
myi2c_w_sda(0);
myi2c_w_scl(0);
}
void myi2c_end()
{
myi2c_w_sda(0);
myi2c_w_scl(1);
myi2c_w_sda(1);
}
void myi2c_sendbyte(uint8_t byte)
{
uint8_t i;
for(i=0;i<8;i++)
{
myi2c_w_sda(byte&(0x80>>i));
myi2c_w_scl(1);
myi2c_w_scl(0);
}
}
uint8_t myi2c_receivebyte()
{
uint8_t i,byte=0x00;
myi2c_w_sda(1);
for(i=0;i<8;i++)
{
myi2c_w_scl(1);
if(myi2c_r_sda()==1){byte |=(0x80>>i);}
myi2c_w_scl(0);
}
return byte;
}
void myi2c_sendack(uint8_t ack)
{
myi2c_w_sda(ack);
myi2c_w_scl(1);
myi2c_w_scl(0);
}
uint8_t myi2c_receiveack()
{
uint8_t ack;
myi2c_w_sda(1);
myi2c_w_scl(1);
ack = myi2c_r_sda();
myi2c_w_scl(0);
return ack;
}
I2C.h
#ifndef __MYI2C_H
#define __MYI2C_H
void myi2c_Init();
void myi2c_start();
void myi2c_end();
void myi2c_sendbyte(uint8_t byte);
uint8_t myi2c_receivebyte();
void myi2c_sendack(uint8_t ack);
uint8_t myi2c_receiveack();
#endif
浙公网安备 33010602011771号