stm32f103c8t6 IIC端口接lcd1602具体实现程序
时间: 2023-09-04 09:06:44 浏览: 140
以下是使用STM32F103C8T6的I2C接口控制LCD1602的程序实现。
首先,需要在STM32CubeMX中配置I2C引脚和时钟,使能I2C总线。然后,使用HAL库提供的函数来控制LCD1602。
```c
#include "stm32f1xx_hal.h"
#include "lcd1602.h"
I2C_HandleTypeDef hi2c1;
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_I2C1_Init(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_I2C1_Init();
lcd1602_init(&hi2c1);
lcd1602_write_string(&hi2c1, "Hello, world!");
while (1)
{
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
static void MX_I2C1_Init(void)
{
hi2c1.Instance = I2C1;
hi2c1.Init.ClockSpeed = 100000;
hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c1.Init.OwnAddress1 = 0;
hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c1.Init.OwnAddress2 = 0;
hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c1) != HAL_OK)
{
Error_Handler();
}
}
static void MX_GPIO_Init(void)
{
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
}
void HAL_Delay(uint32_t Delay)
{
uint32_t tickstart = HAL_GetTick();
while ((HAL_GetTick() - tickstart) < Delay)
{
}
}
void Error_Handler(void)
{
__disable_irq();
while (1)
{
}
}
```
lcd1602.h:
```c
#ifndef __LCD1602_H__
#define __LCD1602_H__
#include "stm32f1xx_hal.h"
#define LCD1602_ADDRESS 0x4E
void lcd1602_init(I2C_HandleTypeDef *hi2c);
void lcd1602_write_string(I2C_HandleTypeDef *hi2c, char *string);
#endif
```
lcd1602.c:
```c
#include "lcd1602.h"
void lcd1602_init(I2C_HandleTypeDef *hi2c)
{
uint8_t init_data[] = {0x38, 0x08, 0x01, 0x06, 0x0C};
HAL_I2C_Master_Transmit(hi2c, LCD1602_ADDRESS, init_data, sizeof(init_data), HAL_MAX_DELAY);
HAL_Delay(100);
}
void lcd1602_write_string(I2C_HandleTypeDef *hi2c, char *string)
{
uint8_t data[2];
while (*string)
{
data[0] = 0x40;
data[1] = *string++;
HAL_I2C_Master_Transmit(hi2c, LCD1602_ADDRESS, data, sizeof(data), HAL_MAX_DELAY);
}
}
```
这个程序使用I2C总线向LCD1602发送数据,通过初始化LCD1602以及写入字符串的函数来实现控制LCD1602。
阅读全文