[N32L43X评测] 3.硬件I2C驱动OLED
[复制链接]
上篇[N32L43X评测] 2.模拟I2C驱动OLED介绍了使用GPIO模拟I2C来驱动OLED显示屏,
此篇介绍使用N32L43x硬件I2C1轮询模式来实现驱动OLED显示屏。
硬件连接
GND —— GND
VCC —— 3.3V
SCL —— PB8
SDA —— PB9
软件代码
I2C1配置参考官方例程:
/**
* [url=home.php?mod=space&uid=159083]@brief[/url] i2c master init
*
*
*/
void i2c_master_init(void)
{
I2C_InitType i2c1_master;
GPIO_InitType i2c1_gpio;
RCC_EnableAPB1PeriphClk(RCC_APB1_PERIPH_I2C1, ENABLE);
RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_AFIO, ENABLE);
RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOB, ENABLE);
/*PB8 -- SCL; PB9 -- SDA*/
GPIO_InitStruct(&i2c1_gpio);
i2c1_gpio.Pin = GPIO_PIN_8 | GPIO_PIN_9;
i2c1_gpio.GPIO_Slew_Rate = GPIO_Slew_Rate_High;
i2c1_gpio.GPIO_Mode = GPIO_Mode_AF_OD;
i2c1_gpio.GPIO_Alternate = GPIO_AF4_I2C1;
i2c1_gpio.GPIO_Pull = GPIO_Pull_Up;
GPIO_InitPeripheral(GPIOB, &i2c1_gpio);
I2C_DeInit(I2C1);
i2c1_master.BusMode = I2C_BUSMODE_I2C;
i2c1_master.FmDutyCycle = I2C_FMDUTYCYCLE_2;
i2c1_master.OwnAddr1 = I2C_MASTER_ADDR;
i2c1_master.AckEnable = I2C_ACKEN;
i2c1_master.AddrMode = I2C_ADDR_MODE_7BIT;
i2c1_master.ClkSpeed = 400000; //400K 100000 100K
I2C_Init(I2C1, &i2c1_master);
I2C_Enable(I2C1, ENABLE);
}
void i2c_master_send(unsigned char* data, int len)
{
unsigned char* sendBufferPtr = data;
while (I2C_GetFlag(I2C1, I2C_FLAG_BUSY));
I2C_GenerateStart(I2C1, ENABLE);
while (!I2C_CheckEvent(I2C1, I2C_EVT_MASTER_MODE_FLAG)); // EV5
I2C_SendAddr7bit(I2C1, I2C_SLAVE_ADDR, I2C_DIRECTION_SEND);
while (!I2C_CheckEvent(I2C1, I2C_EVT_MASTER_TXMODE_FLAG)); // EV6
// send data
while (len-- > 0)
{
I2C_SendData(I2C1, *sendBufferPtr++);
while (!I2C_CheckEvent(I2C1, I2C_EVT_MASTER_DATA_SENDING)); // EV8
}
while (!I2C_CheckEvent(I2C1, I2C_EVT_MASTER_DATA_SENDED)); // EV8-2
I2C_GenerateStop(I2C1, ENABLE);
}
OLED代码变更部分:
//向设备写控制命令
static void OLED_Write_CMD(unsigned char cmd)
{
#ifdef SW_I2C
I2C_Start();
I2C_Send_Byte(0x78);
I2C_Wait_Ack();
I2C_Send_Byte(0x00);
I2C_Wait_Ack();
I2C_Send_Byte(cmd);
I2C_Wait_Ack();
I2C_Stop();
#endif
#ifdef HW_I2C
unsigned char tx_buf[BUF_SIZE] = {0x00, cmd};
i2c_master_send(tx_buf, BUF_SIZE);
#endif
}
//向设备写数据
static void OLED_Write_Date(unsigned char date)
{
#ifdef SW_I2C
I2C_Start();
I2C_Send_Byte(0x78);
I2C_Wait_Ack();
I2C_Send_Byte(0x40);
I2C_Wait_Ack();
I2C_Send_Byte(date);
I2C_Wait_Ack();
I2C_Stop();
#endif
#ifdef HW_I2C
unsigned char tx_buf[BUF_SIZE] = {0x40, date};
i2c_master_send(tx_buf, BUF_SIZE);
#endif
}
运行测试
100Kbps模式
HW_I2C_OLED_100k
400Kbps模式
HW_I2C_OLED_400k
测试代码
N32L43x_HW_I2C_OLED.zip
(517.66 KB, 下载次数: 12)
|