Build a digital clock that displays elapsed time on a LCD. The system displays elapsed time (hh:mm ss.MMM) on a 16x2 text LCD while simultaneously fading an LED using Pulse Width Modulation (PWM) every second. Using the STM32F407ZGT6 microcontroller on the RT-Thread RT-Spark development board.
Step 1: Setting up STM32CubeMX1. System and Clock:
- Open STM32CubeMX and click File then New Project.
- Click MCU/MPU Selector then type STM32F407ZGT6 in Commercial Part Number and double click it.
- In System Core, find SYS then set Debug to Serial Wire.
- In System Core, find RCC then set High Speed Clock (HSE) to Crystal/Ceramic Resonator.
- In the Clock Configuration tab, set the HCLK to 168 MHz. This makes the APB1 Timer clocks run at 84 MHz.
2. GPIO Configuration:
- Locate pins PG1 to PG6 in the chip view.
- Left-click and set each to GPIO_Output.
- Right-click and assign User Labels:
LCD_RS(PG1),LCD_EN(PG2),LCD_D4(PG3),LCD_D5(PG4),LCD_D6(PG5), andLCD_D7(PG6).
3. Timer 2 (The 1ms Interrupt):
- In Pinout & Configuration tab, go to Timers then TIM2. Set Clock Source to Internal Clock.
- In Configuration, under Parameter Settings, set Prescaler (PSC) to
83.
- Set Counter Period (ARR) to
999.
- In the NVIC Settings, enable the TIM2 global interrupt.
4. Timer 3 (The PWM LED Fader):
- In Pinout & Configuration tab, go to Timers then TIM3. Set Clock Source to Internal Clock.
- Set Channel 1 to PWM Generation CH1. (This automatically assigns PA6
- In Configuration, under Parameter Settings, set Prescaler to
83and Counter Period to999to achieve a 1kHz PWM signal.
- Under Project Manager, set your Project Name then Toolchain/IDE to STM32CubeIDE then GenerateCode.
- Under Core, right click Inc then click New then choose HeaderFile. Erase all the written code under it, copy and paste the code I provided. Name the file lcd.h.
- Under Core, right click Src then click New then choose Source File. Erase all the written code under it, copy and paste the code I provided. Name the file lcd.c.
Wiring the LCD:
- VSS: GND
- VDD: 5V
- V0: Middle leg of the 10k potentiometer (outer legs to 5V and GND)
- RS: PG1
- RW: GND (Forces write-only mode)
- EN: PG2
- D4: PG3
- D5: PG4
- D6: PG5
- D7: PG6
- Anode: 5V (through 220Ω resistor)
- Cathode: GND
Wiring the LED:
- Connect the long leg (Anode) of your LED to pin PA6 on the board.
- Connect the short leg (Cathode) to GND through a 220Ω resistor.
- Copy and paste the code I provided.










Comments