STM32F103驱动LCD12864完整教程:并行/串行接口与避坑指南STM32F103 Driving LCD12864: A Complete Guide to Parallel and Serial Interfaces


AI free token/AI免费积分

STM32F103驱动LCD12864完整教程:并行/串行接口与避坑指南

本文来源:https://www.hqwc.cn/a/1462760.html
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。

简介:这是一份基于STM32F103VCT6的LCD12864液晶屏驱动实例工程,面向嵌入式初学者与需要快速上手显示控制的开发者,解决并行接口驱动LCD12864的初始化、时序控制与数据写入问题。资源包共138个文件,约1.27MB,包含32个H头文件、30个C源文件以及uvproj工程配置、hex固件、axf调试文件等,覆盖标准外设库的RCC、GPIO、Flash、ADC等模块,便于直接查阅与编译验证。目前已有857人学习下载。通过该工程可掌握STM32 GPIO推挽输出配置、LCD12864并行通信时序、显示指令(如双行显示、光标移动、清屏)的发送流程,并了解文本与图形显示的内存映射及缓冲绘制思路;实际项目中还可参考节能模式、动态刷新和抗干扰处理等策略,是一份能同时提升底层驱动和工程调试能力的完整参考实现。 做嵌入式开发的朋友应该都有过这样的经历:项目跑起来了,传感器数据也有了,怎么直观地展示出来成了头疼的问题。串口打印虽然方便,但不能每次调试都抱着电脑看日志。所以一块小屏幕成了刚需,而LCD12864(ST7920控制器)凭借内置中英文字库、接口简单、成本低这几点,基本是STM32入门显示方案的默认选项。这篇博文基于我手头实际调通的实例工程,完整梳理STM32F103VCT6驱动LCD12864的全部细节,从硬件连接到驱动代码再到踩坑实录,照着做就能跑起来。

工程里我同时写了并行和串行两种接口的驱动,能覆盖绝大多数使用场景。刚学完GPIO和定时器、想给项目加屏幕的初学者,或者想快速评估方案、直接复用代码的工程师,都可以直接参考。

STM32F103VCT6这颗芯片,很多人习惯叫它“F103大容量型号”,Cortex-M3内核跑到72MHz,256KB Flash,48KB SRAM,LQFP100封装引出了一堆GPIO,算力跑一个简单的显示驱动绰绰有余,资源上完全不紧张。选它来做LCD12864的驱动实例,不是因为性能多强,而是它足够“标准”,市面上你能买到的开发板、核心板、最小系统板里,F103VCT6的出现频率非常高,而且引脚兼容性极好,这个例子跑通之后,换成F103ZET6或者F103RCT6,代码只需要改引脚定义,其他逻辑几乎不动。

LCD12864这块屏,说白了就是128x64分辨率的点阵液晶,控制器以ST7920居多。它最大的吸引力在于内置了GB2312中文字库,也就是说你想显示“温度”“湿度”“电压”这种汉字,不需要自己取模生成点阵数据,直接给编码就能显示,开发效率高出一大截。分辨率不高,但显示4行汉字、每行最多8个汉字,对大部分仪表盘、菜单页面、传感器数值展示这类需求完全够用。它不像OLED那样需要反复刷新防烧屏,也不像LCD1602那样只能显示ASCII字符,价格还便宜,几块钱到十几块钱一片,非常合适入门。

我选这个组合还有一个原因:LCD12864的接口方式很典型,既有并行又有串行,可以同时把STM32的GPIO操作、时序控制、配置引脚复用这几块基本功都练到。后面你换其他型号的液晶或者换别的MCU,这套驱动的思考方式是可以直接迁移的。

LCD12864的ST7920控制器支持三种接口模式:8位并行、4位并行、串行,由模块上的PSB引脚决定。PSB接高电平是并行,接低电平或者悬空是串行。

并行接口需要RS、RW、E三根控制线加8根数据线,一共11个GPIO。它的优势是时序简单、写入速度快,适合需要频繁刷新屏幕的场景,比如做动态波形或者动画。缺点是占引脚多,如果项目里还挂了传感器、按键、继电器,GPIO可能不够用。

串行接口只需要CS、SCLK、SID三根线,省下的引脚去做别的事很香。速度上串行确实比并行慢,但LCD12864本身刷新率不高,正常显示汉字和数值的更新频率下,串行完全不会感觉到卡顿。我用串行模式跑一个每秒刷新10次的温湿度页面,肉眼看起来非常流畅。

在这个工程里,我两种模式都写了驱动代码,默认用并行模式演示,因为并行时序更直观,便于理解ST7920的读写机制。你如果引脚紧张,直接把宏定义的接口模式切换一下就能换成串行,硬件接线上需要把CS、SID、SCLK三根线接到MCU的指定引脚。

工程基于Keil MDK编写,标准外设库和HAL库两种写法我都验过,最终发布的是HAL库版本,因为现在新项目基本都往HAL上靠,CubeMX生成代码也方便。如果你还在用标准外设库,核心逻辑完全一致,把GPIO操作的API换成标准库的写法就行,延时函数保留。

调试器和下载器是很多人第一步就卡住的地方。板载ST-Link的板子,插上USB后电脑不识别,设备管理器里出现未知设备,这种问题八成是驱动没装好,ST-Link V2驱动装一下,或者直接装STM32 ST-LINK Utility,驱动会自动带上。用J-Link的话,注意Windows 10/11下旧版本驱动容易有兼容性问题,直接装新版的J-Link驱动包。

如果板子上没有调试器,只能通过串口下载,那就要看板载USB转串口芯片是哪种,CH340芯片装CH340驱动,CP2102芯片装CP210x驱动,FT232芯片装FTDI驱动,这三种驱动不能混用,认准芯片型号去装。我见过有人拿着CP2102的板子硬装CH340驱动,折腾一晚上没解决,最后发现芯片型号不匹配,白白浪费时间。

LCD12864模块的引脚定义比较统一,绝大多数模块都是20脚或者18脚排针。我用的这块是20脚标准接口,引脚定义如表所示。

我特意把8根数据线放在PD0~PD7,控制线放在PD8~PD10,这样写代码的时候可以利用GPIOD的ODR寄存器低8位一次输出完整数据,效率高也很简洁。如果你用的板子PD口被其他外设占了,换成PE口或者PB口都可以,只要在代码里把端口和引脚宏改掉就行。

对比度调节是LCD12864最容易忽略的环节。模块的V0引脚决定了液晶显示浓淡,很多初学者上电后发现屏幕全黑或者完全看不清,其实不是代码问题,是V0悬空了。正确的做法是用一个10K电位器,两端分别接VDD和GND,中间抽头接V0,通过旋钮调节对比度。有些模块板子上已经焊好了电位器,这类屏买回来直接用就行,如果买的模块没有,就得自己外接一个,否则驱动代码写得再对也看不到显示效果。

背光LED_A不能直接接到3.3V电源上,最好串一个100到220欧姆的限流电阻。我习惯用220欧姆,亮度足够而且不会因为电流过大影响LED寿命。如果你把LED_A接到了5V上,电阻用大一点,330欧姆到470欧姆比较稳妥。LED_K接GND,方向不要反了,背光二极管反接是不会亮的。

还需要注意VDD的电压范围。ST7920的工作电压规格是2.7V到5.5V,所以STM32F103VCT6的3.3V供电是完全没问题的,不用额外升压到5V。如果模块已经板载了5V转3.3V的稳压电路,那就看一下模块背面有没有可跳线的电源选择,没有就统一按3.3V接。

这里要专门说说电平匹配的问题。STM32F103是3.3V逻辑,LCD12864虽然是宽电压芯片,但市面上很多模块在设计时是默认5V供电的,模块上的逻辑电平转换电路不一定做了。如果你的模块VDD接的是5V,而MCU这边是3.3V高电平,ST7920的高电平输入阈值可能刚好处于临界区,表现为时好时坏,偶尔乱码,或者写入数据丢失。这种问题很隐蔽,示波器上看波形也没明显异常,但就是不稳定。

解决办法有三个层级:最省事的办法是让模块也工作在3.3V,ST7920本身支持,只是背光会稍微暗一点点,不影响正常显示。第二是检查模块背面,现在很多模块其实已经板载了电平转换电路,只是丝印没写清楚,看到有74HC245或者MOS管转换芯片就可以放心接5V。第三,如果你的模块必须接5V,又没有电平转换,那就需要外接一块8路的电平转换模块,或者用几个三极管/MOS管做双向转换,不推荐用电阻分压,因为LCD的RST、E等引脚对电平要求比较高,分压容易出问题。

ST7920的初始化看着简单,其实有固定的套路。上电后需要等待内部电源稳定,一般延时40到50毫秒,然后发送功能设定指令0x30,告诉它使用8位并行接口、基本指令集。第一次上电时控制器可能还没完全稳定,所以0x30要连续发两三次,中间加几毫秒延时。之后再依次设置显示开关0x0C,关闭光标和闪烁;清屏0x01,等10毫秒以上让清屏动作完成;最后设置进入点模式0x06,让DDRAM地址自动加1,光标向右移动。

初始化命令顺序不能乱。我刚开始写驱动的时候,把0x0C放在0x30前面,结果屏幕一直白屏,后来对照数据手册才发现,ST7920在基本指令集没有确定之前,后面的显示开关指令是不会被正确解析的。

如果你的模块上有RST引脚,初始化前建议先给一个低电平脉冲,保持1毫秒拉高,这样能确保LCD内部状态机复位到已知位置。直接把RST接3.3V也不是不能用,但在上电瞬间可能出现一次花屏,偶尔需要按一次复位键才能正常显示,原因就是RST没有手动复位。

并行模式下,写入一个字节分三个步骤:设置RS的电平,确定当前是命令还是数据;把要写的内容放到数据总线上;给E引脚一个高脉冲,ST7920在E的下降沿锁存总线上的数据。整个过程要注意时序上必须保证建立时间,RS和RW的电平要先稳定,E脉冲再拉高,否则数据可能被错误锁存。

我习惯把写入拆成两个函数,LCD12864_WriteCommand负责发命令,LCD12864_WriteData负责发数据,内部共用一个字节写函数,用isData标志区分。

有人问数据手册要求E脉冲宽度至少多长,实际上ST7920的时序要求并不苛刻,E高电平保持时间最小约450ns,72MHz主频下两条NOP指令就已经有几ns到十几ns,再加上HAL库API本身的调用开销,完全能满足要求。但如果你用GPIO模拟函数、中间夹杂了太多其他操作,适当加延时没有坏处。

并行模式下我还实现了一个读状态的函数,用来检测BF忙标志位。写命令前先读一下,如果BF为1说明LCD还在处理内部操作,暂时不能接收新数据。这个函数在显示批量数据时很重要,不加的话偶发丢字,加了就非常稳定。不过读操作需要把数据线改成输入模式,代码复杂度会上升,如果显示频率不是特别高,等待延时的方式也够用——我在实际工程里两种方式都测过,最终选择了延时方案,因为更简单,不占用额外的GPIO模式切换时间。

串行模式是引脚紧张时的救星。ST7920的串行通信格式和SPI有点像,但它不是标准SPI协议,而是一种类SPI的三线方式,需要自己用GPIO模拟。CS片选拉低,SCLK提供时钟,SID逐位发送数据,数据在高电平期间被采样。

串行每传输一个字节,实际分成两个阶段:先发送一个帧头字节,0xF8表示后面跟的是命令,0xFA表示后面跟的是数据,然后数据本身要拆成高4位和低4位两次发送,每次发送时先发4位有效数据,再补4个0。这个格式我第一次看的时候有点懵,后来对着逻辑分析仪才看明白,ST7920串行模式下每个字节实际上要传输24个bit。

注意我这里的LCD12864_SendBit函数每次只发送一位,实际操作时也可以把SendBit改成SendByte函数,参数是8位数据,内部循环8次发送,逻辑更紧凑。串行模式不需要RW和E这两根线,把它们固定接GND就行,PSB必须接低电平,否则模块仍然工作在并行模式,串行数据根本进不去。

显示字符时,ST7920的DDRAM地址映射是很多人写错的重点。屏幕分成4行,每一行的起始地址并不是从上到下顺序排列的,第一行是0x80,第二行是0x90,第三行跳回到0x88,第四行是0x98。这个设计初看很奇怪,实际是因为ST7920的DDRAM在物理上分为上下两个半屏,地址行号和水平坐标组合而成的,第三四行从0x88和0x98开始是为了配合内部字库的取模顺序。

写一个定位函数,把行号和列号换算成DDRAM地址,再调用写命令接口设置地址,之后连续写数据即可。

有一个细节需要提醒:LCD12864在汉字模式下,DDRAM每个地址对应一个16x16点阵的汉字位置,所以一个汉字占一个地址,而ASCII字符是8x16点阵,一个地址位置能放下两个ASCII字符,但在写地址的时候仍然按地址加1的方式递增。实际工程中,我遇到过一个很常见的坑:用同一套DDRAM地址函数去显示字符串,中英文混排时经常出现“英文往右串位、汉字对不齐”的情况,这是因为没有单独处理ASCII的宽度。如果只显示纯中文,地址逻辑很简单;如果混排中英文,需要自己定义一个“半角/全角”判断函数,ASCII字符在写DDRAM前先写一个0x20空格占位,这样光标移动才是正确的。

这个函数我实际测试下来,配合我手头的LCD12864模块,中英文混排显示基本正常。不同厂家模块使用的ST7920版本略有差异,极少数模块直接写ASCII就能正常显示,不需要补0x20,如果你的模块显示出来有间隔或者串位,把补空格那段去掉试试。

ST7920除了文本模式,还内置了GDRAM,也就是图形显示区域,可以按像素点控制屏幕上的任意一个点。进入绘图模式需要先发送0x34切换到扩展指令集,再发0x36使能绘图显示。

GDRAM的地址规划和DDRAM一样反直觉:它把屏幕分成上下两个区域,每个区域水平方向8个字节、垂直方向32行。写入一个像素点,一般需要先读回当前GDRAM地址的两个字节数据,把对应位置1或清0,再写回去。因为GDRAM不支持单独的位操作,直接写整字节数据会覆盖掉原来已有的图案。

绘图模式的一个典型用途是显示自定义的波形曲线或者简单的图标,当然也可以自己定义汉字点阵,绕过内置字库的限制。我在这块屏上跑过一个简易的心率波形,每秒钟采样50个点,用GDRAM把点画出来,效果完全可以接受。不过要注意,绘图模式显示期间,文本模式显示的内容会受到影响,两者共用一块显示区域,使用前需要明确当前处于哪种模式,切换模式时要重新发送功能设定指令。

LCD12864常见的问题,很多不是代码逻辑错误,而是硬件连接和初始化细节导致的。我整理了一个排查表,按出现频率排列。

我最常遇到的是V0没接电位器导致的“全黑假死”,这个问题特别迷惑,因为程序怎么查都查不出毛病,最后发现是硬件问题。所以拿到新模块,第一步先接好电位器调对比度,再谈驱动代码。

调试LCD12864的过程里,很大一部分时间其实花在让代码下载到芯片上。板载ST-Link的板子,电脑不识别设备,设备管理器里出现黄色感叹号,基本都是驱动问题。解决方法是先装ST-Link V2驱动,然后是STM32 ST-LINK Utility或者STM32CubeProgrammer,一般来说装完这些开发软件,驱动也就自动装好了。需要注意的是,有些精简版系统会把驱动签名验证机制关闭,ST-Link驱动在这种环境下会装不上,开一下测试模式或者换一个官方驱动包。

用J-Link调试的时候,旧版驱动在Windows 10以上容易出现“无法连接”“无法识别”的报错,直接到官网下载最新版J-Link驱动可以解决。串口下载方式的坑更多,核心一点是:板子上的USB转串口芯片型号决定了你要装哪个驱动,CH340、CP2102、FT232三种芯片对应三种不同的驱动,不能通用。我见过有人把CP2102的板子当成CH340来装,折腾了一晚上,最后用万能驱动软件扫描才装上,但其实只要看一眼芯片丝印,几分钟就能解决。

STM32F103 Driving LCD12864: A Complete Guide to Parallel and Serial Interfaces

本文来源:https://www.hqwc.cn/a/1462760.html
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。

Overview: This is an LCD12864 LCD driver example project based on the STM32F103VCT6, aimed at embedded beginners and developers who need to quickly get started with display control. It addresses the issues of initialization, timing control, and data writing for driving the LCD12864 via a parallel interface. The resource package contains a total of 138 files, approximately 1.27 MB, including 32 H header files, 30 C source files, as well as uvproj project configurations, hex firmware, axf debug files, etc. It covers modules such as RCC, GPIO, Flash, and ADC from the Standard Peripheral Library, making it convenient for direct reference and compilation verification. Currently, 857 people have downloaded it for study. Through this project, you can master the STM32 GPIO push-pull output configuration, the LCD12864 parallel communication timing, and the sending process for display commands (such as two-line display, cursor movement, and screen clearing). You can also understand the memory mapping for text and graphics display, as well as the concept of buffer rendering. In actual projects, you can also refer to strategies such as power-saving mode, dynamic refresh, and anti-interference processing. This is a complete reference implementation that can simultaneously enhance both low-level driver and project debugging capabilities.

In the project, I wrote drivers for both parallel and serial interfaces, which can cover the vast majority of use cases. This can be directly referenced by beginners who have just learned about GPIOs and timers and want to add a screen to their project, or by engineers who want to quickly evaluate a solution and directly reuse code.

The STM32F103VCT6 chip, which many people are accustomed to calling the "F103 high-capacity model," features a Cortex-M3 core running at 72 MHz, 256 KB of Flash, 48 KB of SRAM, and an LQFP100 package that provides a множество of GPIO pins. Its computing power is more than sufficient to run a simple display driver, and its resources are completely unconstrained. The reason for choosing it as an example for the LCD12864 driver is not because of its powerful performance, but because it is sufficiently "standard." Among the development boards, core boards, and minimum system boards available on the market, the F103VCT6 appears very frequently, and its pin compatibility is excellent. After this example runs successfully, switching to the F103ZET6 or F103RCT6 only requires changing the pin definitions in the code, with almost no changes to the other logic.

The LCD12864 screen is essentially a dot-matrix LCD with a resolution of 128x64, and the majority of its controllers are ST7920. Its biggest appeal lies in its built-in GB2312 Chinese character library. This means that if you want to display Chinese characters like "temperature," "humidity," and "voltage," you don't need to create dot-matrix data yourself. You can simply provide the encoding, and the characters will be displayed, greatly improving development efficiency. The resolution is not high, but it can display 4 lines of Chinese characters, with a maximum of 8 Chinese characters per line. This is perfectly sufficient for most needs such as instrument panels, menu pages, and sensor value displays. Unlike OLEDs, it doesn't require repeated refreshes to prevent burn-in, and unlike the LCD1602, it isn't limited to displaying ASCII characters. It's also inexpensive, costing just a few dollars to a dozen dollars per unit, making it an excellent choice for beginners.

There is another reason why I chose this combination: The interface method of the LCD12864 is very typical, with both parallel and serial interfaces. This allows you to simultaneously practice the basic skills of STM32 GPIO operations, timing control, and pin multiplexing configuration. Later, if you switch to another model of LCD or another MCU, the way of thinking behind this driver can be directly applied.

The ST7920 controller of the LCD12864 supports three interface modes: 8-bit parallel, 4-bit parallel, and serial, which are determined by the PSB pin on the module. When the PSB pin is connected to a high level, it is in parallel mode; when it is connected to a low level or left floating, it is in serial mode.

The parallel interface requires three control lines (RS, RW, E) and eight data lines, for a total of 11 GPIOs. Its advantages are simple timing and fast write speed, making it suitable for scenarios that require frequent screen refreshes, such as displaying dynamic waveforms or animations. The disadvantage is that it takes up a lot of pins. If the project also includes sensors, buttons, and relays, there may not be enough GPIOs.

The serial interface only requires three wires: CS, SCLK, and SID. It's great to have the extra pins available for other purposes. In terms of speed, serial is indeed slower than parallel, but the LCD12864 itself does not have a high refresh rate. Under the normal update frequency for displaying Chinese characters and numerical values, serial will not feel laggy at all. I used the serial mode to run a temperature and humidity page that refreshes 10 times per second, and it looks very smooth to the naked eye.

In this project, I wrote driver code for both modes, and the default demonstration is in parallel mode because the parallel timing is more intuitive, making it easier to understand the read-write mechanism of the ST7920. If you are short on pins, you can simply switch the interface mode defined by the macro to serial. For the hardware connections, you need to connect the three wires CS, SID, and SCLK to the designated pins of the MCU.

The project was written using Keil MDK. I have tested both the Standard Peripheral Library and the HAL Library approaches, and the final release is the HAL Library version because most new projects now tend to use HAL, and CubeMX makes code generation convenient. If you are still using the Standard Peripheral Library, the core logic is exactly the same. Simply change the API for GPIO operations to the Standard Peripheral Library's syntax, and keep the delay function.

The debugger and downloader are where many people get stuck at the very first step. If the board has an onboard ST-Link and the computer does not recognize it after plugging in the USB, and an unknown device appears in the Device Manager, this problem is most likely due to the driver not being properly installed. Install the ST-Link V2 driver, or directly install the STM32 ST-LINK Utility, and the driver will be automatically included. When using J-Link, be aware that older versions of the driver are prone to compatibility issues on Windows 10/11. Instead, directly install the latest version of the J-Link driver package.

If there is no debugger on the board and you can only download via the serial port, then you need to check which type of USB-to-serial chip is on the board. The CH340 chip requires the CH340 driver, the CP2102 chip requires the CP210x driver, and the FT232 chip requires the FTDI driver. These three drivers cannot be used interchangeably. Make sure to install the correct driver based on the chip model. I've seen people stubbornly install the CH340 driver on a board with a CP2102 chip. They struggled with it all night without resolving the issue, and eventually realized that the chip models didn't match, wasting their time for nothing.

The pin definitions of the LCD12864 module are relatively uniform, and most modules have 20-pin or 18-pin headers. The one I'm using has a standard 20-pin interface, and the pin definitions are shown in the table.

I deliberately placed the 8 data lines on PD0~PD7 and the control lines on PD8~PD10, so that when writing code, the lower 8 bits of the GPIOD ODR register can be used to output complete data at once, which is both efficient and concise. If the PD port on the board you are using is occupied by other peripherals, you can switch to the PE port or the PB port. You just need to change the port and pin macros in the code.

Contrast adjustment is the most easily overlooked aspect of the LCD12864. The V0 pin of the module determines the brightness of the LCD display. Many beginners find that the screen is completely black or completely illegible after powering up. In fact, it is not a problem with the code, but rather that the V0 pin is left unconnected. The correct approach is to use a 10K potentiometer, with its two ends connected to VDD and GND respectively, and the middle tap connected to V0, allowing contrast adjustment via the knob. Some module boards already have potentiometers soldered on them. These types of displays can be used directly after purchase. If the purchased module does not have one, you will need to connect one externally yourself; otherwise, even if the driver code is written correctly, you will not be able to see the display effect.

The backlight LED_A cannot be directly connected to the 3.3V power supply. It is best to connect a 100 to 220 ohm current-limiting resistor in series. I usually use 220 ohms, which provides sufficient brightness and does not affect the LED's lifespan due to excessive current. If you connect LED_A to 5V, use a larger resistor; 330 ohms to 470 ohms is more reliable. Connect LED_K to GND. Do not reverse the direction. The backlight diode will not light up if it is connected in reverse.

You also need to pay attention to the voltage range of VDD. The operating voltage specification of the ST7920 is 2.7V to 5.5V, so the 3.3V power supply of the STM32F103VCT6 is perfectly fine, and there is no need to additionally boost the voltage to 5V. If the module already has an on-board 5V-to-3.3V voltage regulator circuit, then check the back of the module to see if there is a jumper-selectable power supply option. If not, connect it to 3.3V across the board.

Here, we need to specifically address the issue of level matching. The STM32F103 is a 3.3V logic device. Although the LCD12864 is a wide-voltage chip, many modules on the market are designed with a default 5V power supply, and the logic level conversion circuit on the module may not have been implemented. If your module's VDD is connected to 5V, and the MCU side is at a 3.3V high level, the ST7920's high-level input threshold may be right at the critical point, resulting in inconsistent performance, occasional garbled characters, or loss of written data. This kind of problem is very subtle. The waveform on the oscilloscope does not show any obvious abnormalities, but it is simply unstable.

There are three levels of solutions: The easiest way is to have the module also operate at 3.3V, which the ST7920 itself supports. The backlight will only be slightly dimmer, and this will not affect normal display. The second is to check the back of the module. Many modules nowadays actually already have a level-shifting circuit on-board, but the silkscreen is not clearly marked. If you see a 74HC245 or a MOS transistor level-shifting chip, you can safely connect 5V. Third, if your module must be connected to 5V and there is no level conversion, then you need to connect an external 8-channel level conversion module, or use several transistors/MOS transistors for bidirectional conversion. It is not recommended to use resistor voltage division, because the RST, E, and other pins of the LCD have relatively high level requirements, and voltage division is prone to problems.

The initialization of the ST7920 looks simple, but there is actually a fixed procedure. After power-up, it is necessary to wait for the internal power supply to stabilize, usually with a delay of 40 to 50 milliseconds, and then send the function setting command 0x30 to instruct it to use an 8-bit parallel interface and the basic instruction set. The controller may not be fully stable when powered on for the first time, so 0x30 needs to be sent two or three times in succession, with a few milliseconds of delay in between. After that, set the display switch 0x0C in sequence to turn off the cursor and blinking; clear the screen with 0x01, and wait for more than 10 milliseconds to allow the screen clearing action to complete; finally, set the entry mode to 0x06, so that the DDRAM address automatically increments by 1 and the cursor moves to the right.

The order of initialization commands cannot be mixed up. When I first started writing the driver, I put 0x0C before 0x30, and as a result, the screen remained white. Later, I checked the datasheet and discovered that the ST7920 would not correctly interpret the subsequent display switch commands until the basic instruction set had been determined.

If your module has an RST pin, it is recommended to apply a low-level pulse before initialization and keep it high for 1 millisecond. This ensures that the LCD's internal state machine is reset to a known position. It is not impossible to directly connect RST to 3.3V, but a scrambled screen may occur at the moment of power-up, and occasionally it is necessary to press the reset button once for normal display. The reason is that RST is not manually reset.

In parallel mode, writing a byte is done in three steps: set the RS level to determine whether it is a command or data; place the content to be written on the data bus; give the E pin a high pulse, and the ST7920 latches the data on the bus at the falling edge of E. Throughout the entire process, it is important to ensure the setup time in terms of timing. The levels of RS and RW must stabilize first, and then the E pulse is raised. Otherwise, the data may be incorrectly latched.

I usually split the write operation into two functions: LCD12864_WriteCommand is responsible for sending commands, and LCD12864_WriteData is responsible for sending data. Internally, they share a single-byte write function, differentiated by the isData flag.

Someone asked how long the E pulse width needs to be according to the datasheet. In reality, the timing requirements of the ST7920 are not stringent. The minimum E high-level hold time is approximately 450 ns. At a 72 MHz clock frequency, two NOP instructions already take several to over ten nanoseconds. Considering the overhead of calling the HAL library API itself, these requirements can be fully met. However, if you use GPIO simulation functions and there are too many other operations interspersed in between, it doesn't hurt to add an appropriate delay.

In parallel mode, I also implemented a function to read the status, which is used to detect the BF busy flag. Read it before writing the command. If BF is 1, it means that the LCD is still processing internal operations and cannot receive new data for the time being. This function is important when displaying bulk data. Without it, characters are occasionally lost, but with it, the display is very stable. However, the read operation requires changing the data line to input mode, which increases the complexity of the code. If the display frequency is not particularly high, the wait-and-delay method is also sufficient. I have tested both methods in actual projects and ultimately chose the delay method because it is simpler and does not take up additional time for GPIO mode switching.

Serial mode is a lifesaver when pins are scarce. The serial communication format of the ST7920 is somewhat similar to SPI, but it is not a standard SPI protocol. Instead, it is an SPI-like three-wire method that needs to be simulated using GPIO. The CS chip select is pulled low, SCLK provides the clock, SID sends data bit by bit, and the data is sampled during the high logic level.

Each time a byte is transmitted serially, it is actually divided into two stages: first, a frame header byte is sent. 0xF8 indicates that a command follows, and 0xFA indicates that data follows. Then, the data itself is split into the upper 4 bits and the lower 4 bits and sent twice. Each time it is sent, 4 bits of valid data are sent first, followed by 4 zeros. I was a bit confused when I first saw this format. Later, I understood it with the help of a logic analyzer. In the ST7920 serial mode, each byte actually transmits 24 bits.

Note that the LCD12864_SendBit function here only sends one bit at a time. In actual operation, SendBit can also be changed to the SendByte function, with the parameter being 8-bit data, and the internal loop sending 8 times, making the logic more compact. The serial mode does not require the RW and E lines. Simply connect them permanently to GND. The PSB must be connected to a low level; otherwise, the module will still operate in parallel mode, and serial data will not be able to enter at all.

When displaying characters, the DDRAM address mapping of the ST7920 is a key point that many people get wrong. The screen is divided into 4 lines, and the starting address of each line is not arranged in order from top to bottom. The first line is 0x80, the second line is 0x90, the third line jumps back to 0x88, and the fourth line is 0x98. This design seems strange at first glance, but in reality, it is because the ST7920's DDRAM is physically divided into two halves, upper and lower, and the addresses are formed by combining the row numbers and horizontal coordinates. The third and fourth rows start from 0x88 and 0x98, respectively, to align with the bit-mapping order of the internal character set.

Write a positioning function to convert the row and column numbers into DDRAM addresses, then call the write command interface to set the address, and finally write the data continuously.

There is one detail to note: In Chinese character mode on the LCD12864, each DDRAM address corresponds to the position of a 16x16-pixel Chinese character, so one Chinese character occupies one address. ASCII characters, on the other hand, are 8x16 pixels, so one address position can accommodate two ASCII characters. However, when writing addresses, they still increment by adding 1 to the address. In actual projects, I have encountered a very common pitfall: when using the same set of DDRAM address functions to display strings, "English characters shift to the right, and Chinese characters are misaligned" often occurs when mixing Chinese and English. This is because the width of ASCII characters is not handled separately. If only Chinese characters are displayed, the address logic is straightforward. However, when mixing Chinese and English characters, you need to define a "half-width/full-width" determination function yourself. For ASCII characters, a 0x20 space placeholder should be written before writing to the DDRAM, ensuring correct cursor movement.

I have actually tested this function with the LCD12864 module I have on hand, and the mixed display of Chinese and English characters is generally normal. The ST7920 versions used by modules from different manufacturers vary slightly. A very small number of modules can display ASCII characters normally by writing them directly, without the need to add 0x20. If your module displays characters with gaps or misalignments, try removing the part that adds spaces.

In addition to text mode, the ST7920 also has a built-in GDRAM, i.e., a graphics display area, which can control any point on the screen on a pixel-by-pixel basis. To enter graphics mode, you must first send 0x34 to switch to the extended instruction set, and then send 0x36 to enable graphics display.

The address layout of GDRAM is just as counterintuitive as that of DDRAM: it divides the screen into two areas, upper and lower, each with 8 bytes horizontally and 32 rows vertically. To write a pixel, it is generally necessary to first read back the two bytes of data at the current GDRAM address, set the corresponding bit to 1 or clear it to 0, and then write it back. Since GDRAM does not support individual bit operations, directly writing whole-byte data will overwrite the existing pattern.

A typical use of graphics mode is to display custom waveforms or simple icons. Of course, you can also define your own Chinese character dot matrix to bypass the limitations of the built-in font library. I ran a simple heart rate waveform on this display, sampling 50 points per second and using GDRAM to plot the points. The result was perfectly acceptable. However, it should be noted that during the display in graphics mode, the content displayed in text mode will be affected. Both modes share the same display area, so it is necessary to determine which mode is currently active before use. When switching modes, the function setting command must be sent again.

Many of the common issues with the LCD12864 are not due to logical errors in the code, but rather to hardware connections and initialization details. I have compiled a troubleshooting list, sorted by frequency of occurrence.

The most common issue I encounter is the "completely black screen freeze" caused by V0 not being connected to the potentiometer. This problem is particularly puzzling because no matter how much I check the program, I can't find any issues, and it ultimately turns out to be a hardware problem. So, when you get a new module, the first step is to connect the potentiometer to adjust the contrast, and then worry about the driver code.

During the process of debugging the LCD12864, a significant amount of time is actually spent on downloading the code to the chip. For boards with an onboard ST-Link, if the computer does not recognize the device and a yellow exclamation mark appears in the Device Manager, it is usually a driver issue. The solution is to first install the ST-Link V2 driver, followed by the STM32 ST-LINK Utility or STM32CubeProgrammer. Generally, once these development software tools are installed, the driver will be installed automatically. It should be noted that some lightweight systems disable the driver signature verification mechanism, and the ST-Link driver cannot be installed in such an environment. Enable test mode or switch to an official driver package.

When debugging with J-Link, older versions of the driver are prone to "Unable to connect" and "Unrecognized" errors on Windows 10 and later. This can be resolved by directly downloading the latest version of the J-Link driver from the official website. There are more pitfalls with the serial port download method. The key point is that the model of the USB-to-serial chip on the board determines which driver you need to install. The three chips – CH340, CP2102, and FT232 – correspond to three different drivers and are not interchangeable. I've seen people try to install a CP2102 board as if it were a CH340. They struggled with it all night and finally managed to install it after scanning with a universal driver software. But really, all it takes is a quick look at the chip's silkscreen, and the problem can be solved in just a few minutes.

暂无评论,快来发表第一条评论吧!No comments yet. Be the first!

📮 需求咨询📮 Inquiry