今天搞了一下MM32驱动24C02。
原理图:
代码:
#include "uart.h"
#include "sys.h"
#include "delay.h"
#include "i2c.h"
int main(void)
{
delay_init();
uart_initwBaudRate(115200);
printf("uart ok\r\n");
I2CMasterTest(I2C1); //I2C收发数据
while(1) //无限循环
{
}
}
#include "HAL_conf.h"
#include "uart.h"
volatile unsigned char rx_flag = 0;
volatile unsigned char tx_flag = 0;
extern uint16_t I2C_DMA_DIR;
unsigned char tx_buffer0[16] = {0x55,1,2,3,4,5,6,7,8,9,0xa,0xb,0xc,0xd,0xe,0xf};
unsigned char rx_buffer0[16] ;
volatile unsigned short txData_Number = 0;
volatile unsigned short txData_count = 0;
void uart_printf( const char * ctrl1, ...);
//#define FLASH_DEVICE_ADDR 0xa8
#define FLASH_DEVICE_ADDR 0xa0
/********************************************************************************************************
**函数信息 :I2CInitMasterMode(I2C_TypeDef *I2Cx,unsigned long apb_mhz,unsigned long i2c_baud_rate) //unit is Khz
**功能描述 :初始化I2C
**输入参数 :I2C_TypeDef *I2Cx,选择I2C1,I2C2
**输出参数 :无
********************************************************************************************************/
void I2CInitMasterMode()
{
I2C_InitTypeDef I2C_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE); //开启GPIOA,GPIOB时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOB, &GPIO_InitStructure);
I2C_InitStructure.I2C_Mode = I2C_Mode_MASTER;
I2C_InitStructure.I2C_OwnAddress = FLASH_DEVICE_ADDR;
I2C_InitStructure.I2C_Speed = I2C_Speed_STANDARD;
I2C_InitStructure.I2C_ClockSpeed = 100000;
I2C_Init(I2C1, &I2C_InitStructure);
I2C_Cmd(I2C1, ENABLE);
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOB,GPIO_PinSource6,GPIO_AF_1);
GPIO_PinAFConfig(GPIOB,GPIO_PinSource7,GPIO_AF_1);
}
/********************************************************************************************************
**函数信息 :I2CMasterTest(I2C_TypeDef *I2Cx)
**功能描述 :I2C接收发送数据测试程序
**输入参数 :I2C_TypeDef *I2Cx,选择I2C1,I2C2
**输出参数 :无
********************************************************************************************************/
unsigned char rxBuffer[16] = {0};
void I2CMasterTest(I2C_TypeDef *I2Cx)
{
unsigned char i;
I2CInitMasterMode();
I2CMasterWrite(I2C1,FLASH_DEVICE_ADDR, 16*1, 16, tx_buffer0 );
for(i = 0; i < 16 ;i ++)
{
printf("TX data is: %x \r\n", tx_buffer0);
}
I2CMasterRead(I2C1,FLASH_DEVICE_ADDR, 16*1, 16, rx_buffer0 );
}
效果图:
工程:
I2C_AT24C08.rar
(339.89 KB)
|
|