基于stm32f103c8t6控制lcd12864的程序
时间: 2023-09-03 19:12:11 浏览: 45
以下是基于STM32F103C8T6控制LCD12864的程序:
```c
#include "stm32f10x.h"
#include "delay.h"
#define RS GPIO_Pin_0
#define RW GPIO_Pin_1
#define EN GPIO_Pin_2
#define DB0 GPIO_Pin_8
#define DB1 GPIO_Pin_9
#define DB2 GPIO_Pin_10
#define DB3 GPIO_Pin_11
#define DB4 GPIO_Pin_12
#define DB5 GPIO_Pin_13
#define DB6 GPIO_Pin_14
#define DB7 GPIO_Pin_15
#define DATA_PORT GPIOE
#define CMD_PORT GPIOB
void LCD_Init(void);
void LCD_Write_Cmd(uint8_t cmd);
void LCD_Write_Data(uint8_t data);
void LCD_Clear(void);
void LCD_Set_Cursor(uint8_t row, uint8_t col);
void LCD_Write_Char(uint8_t row, uint8_t col, uint8_t data);
void LCD_Write_String(uint8_t row, uint8_t col, char *str);
int main(void)
{
SystemInit();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOE, ENABLE);
LCD_Init();
LCD_Write_String(0, 0, "Hello World!");
while (1)
{
// Do something
}
}
void LCD_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
// Enable GPIOB and GPIOE clocks
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOE, ENABLE);
// Configure control pins as output push-pull
GPIO_InitStruct.GPIO_Pin = RS | RW | EN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(CMD_PORT, &GPIO_InitStruct);
// Configure data pins as output push-pull
GPIO_InitStruct.GPIO_Pin = DB0 | DB1 | DB2 | DB3 | DB4 | DB5 | DB6 | DB7;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(DATA_PORT, &GPIO_InitStruct);
// Wait for LCD to power up
Delay_ms(100);
// Function Set
LCD_Write_Cmd(0x38);
Delay_ms(5);
// Display On/Off Control
LCD_Write_Cmd(0x0C);
Delay_ms(5);
// Clear Display
LCD_Clear();
Delay_ms(5);
// Entry Mode Set
LCD_Write_Cmd(0x06);
Delay_ms(5);
}
void LCD_Write_Cmd(uint8_t cmd)
{
GPIO_ResetBits(CMD_PORT, RS);
GPIO_ResetBits(CMD_PORT, RW);
Delay_us(1);
GPIO_SetBits(CMD_PORT, EN);
Delay_us(1);
GPIO_Write(DATA_PORT, cmd);
Delay_us(1);
GPIO_ResetBits(CMD_PORT, EN);
Delay_us(50);
}
void LCD_Write_Data(uint8_t data)
{
GPIO_SetBits(CMD_PORT, RS);
GPIO_ResetBits(CMD_PORT, RW);
Delay_us(1);
GPIO_SetBits(CMD_PORT, EN);
Delay_us(1);
GPIO_Write(DATA_PORT, data);
Delay_us(1);
GPIO_ResetBits(CMD_PORT, EN);
Delay_us(50);
}
void LCD_Clear(void)
{
LCD_Write_Cmd(0x01);
Delay_ms(2);
}
void LCD_Set_Cursor(uint8_t row, uint8_t col)
{
uint8_t address;
switch (row)
{
case 0:
address = col;
break;
case 1:
address = col + 0x40;
break;
case 2:
address = col + 0x10;
break;
case 3:
address = col + 0x50;
break;
}
LCD_Write_Cmd(0x80 | address);
Delay_us(50);
}
void LCD_Write_Char(uint8_t row, uint8_t col, uint8_t data)
{
LCD_Set_Cursor(row, col);
LCD_Write_Data(data);
Delay_us(50);
}
void LCD_Write_String(uint8_t row, uint8_t col, char *str)
{
LCD_Set_Cursor(row, col);
while (*str)
{
LCD_Write_Data(*str++);
}
}
```
这个程序中,我们定义了与LCD相关的引脚,以及一些函数,例如LCD初始化、写命令、写数据、清屏、设置光标、写字符和写字符串。在主函数中,我们初始化LCD并写入“Hello World!”。在while循环中,你可以添加你自己的代码。