STM32——HAL库开发笔记9(I2C实践篇)(参考来源:b站铁头山羊)
本实验旨在点亮一个0.96寸OLED屏幕,板载LED点亮的同时,OLED屏幕也点亮。
一、OLED屏幕说明(0.96寸)
该屏幕有四个引脚,其中VCC接电源正极,GND接地,SCL和SDA是屏幕的I2C接口。SCL为I2C接口的串行时钟线,SDA为I2C的串行数据线。
二、STM32CubeMX配置
设置I2C接口
参数说明:
1、Master Features: 主机参数
2、Slave Features: 从机参数
3、I2C Speed Mode: 速度等级
我们选择快速模式,即Fast Mode
4、I2C Clock Speed(HZ) : 设置波特率 ——我们设置为快速模式下最大即400000
Fast Mode Duty Cycle : 快速模式下时钟信号的占空比,我们一般选择2/1占空比
5、Clock No Stretch Mode :时钟没有扩展模式
6、 Primary Address Length selection:从设备地址长度
7、Dual Address Ackonwledged:双地址模式
8、Primary slave address:从设备初始地址
9、General Call address detection:可寻址所有设备的地址
配置好之后如下图:
三、电路连接
通过查看手册得知,该屏幕的地址为:01111000 即:0x78
四、相关指令
uint8_t commands = {
0x00, //命令流
0x8d,0x14, //使能电荷泵
0xaf, //打开屏幕的开关
0xa5, //让屏幕全亮
}
五、编程接口
HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c,
uint16_t DevAddress,
uint8_t *pData,
uint16_t Size,
uint32_t Timeout)
作用: 向从机写数据
HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c,
uint16_t DevAddress,
uint8_t *pData,
uint16_t Size,
uint32_t Timeout)
作用: 向从机读数据
参数说明:
hi2c : 填写I2C句柄的指针 &hi2c1
DevAddress : 填写从机地址 0x78
pData : 填写要发送的数据
Size : 填写要发送的数量,以字节为单位
Timeout : 超时时间,单位为ms 如果超过了超时时间会停止运行并且返回一个错误,一般不使用,我们填
写HAL_MAX_DELAY,表示无限期等下去。
返回值 : 返回数据发送的结果(成功还是失败)
HAL_OK ——成功
其他返回值 ——发送失败
六、编程思路
1、首先声明一个数组存放和OLED屏幕相关的命令
uint8_t commands[] = {0x00,0x8d,0x14,0xaf,0xa5};
2、调用HAL_I2C_Master_Transmit()将其发送出去。
HAL_I2C_Master_Transmit(&hi2c1, //i2c句柄
0x78, //从机地址
commands, //要写入的数据
sizeof(commands), //传输的数量
HAL_MAX_DELAY //超时时间
);
3、加上while循环,防止程序跑飞。
通过查阅手册,我们可以得知该屏幕有一个状态字,这个状态字由8个比特位组成。
4、申明一个变量存储读回的字节
uint8_t dataRcvd;
5、调用HAL_I2C_Master_Receive()读取字节
HAL_I2C_Master_Receive(&hi2c1,
0x78,
&dataRcvd, //接收缓冲区的指针
1,
HAL_MAX_DELAY)
6、判断D6的值。若D6=0则屏幕开启,板载LED点亮;D6=1,屏幕关闭,板载LED熄灭。
if ((dataRcvd&(1<<6) == 0)
{
HAL_GPIO_WritePin(GPIOC , GPIO_PIN_13 , GPIO_PIN_SET);
}
else
{
HAL_GPIO_WritePin(GPIOC , GPIO_PIN_13 , GPIO_PIN_RESET);
}
七、代码(main.c)
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2025 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_I2C1_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
uint8_t commands[] = {0x00,0x8d,0x14,0xaf,0xa5};
HAL_I2C_Master_Transmit(&hi2c1, 0x78, commands,sizeof(commands),HAL_MAX_DELAY);
uint8_t dataRcvd;
HAL_I2C_Master_Receive(&hi2c1,0x78, &dataRcvd, 1,HAL_MAX_DELAY);
if ((dataRcvd & (0x01 << 6)) == 0)
{
HAL_GPIO_WritePin(GPIOC , GPIO_PIN_13 , GPIO_PIN_SET);
}
else
{
HAL_GPIO_WritePin(GPIOC , GPIO_PIN_13 , GPIO_PIN_RESET);
}
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
{
Error_Handler();
}
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
最后将代码编译下载,就可以看到板载LED点亮,OLED屏幕也亮。
作者:SRAL