Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 95 additions & 49 deletions examples/Dynamic_loading_font_example.py
Original file line number Diff line number Diff line change
@@ -1,64 +1,110 @@
#
# Command line for running this example on the unix port from examples directory:
# MICROPYPATH=./:../lib ../../../ports/unix/micropython -i Dynamic_loading_font_example.py
#
"""
LVGL Dynamic Font Loading Example

import usys as sys
sys.path.append('') # See: https://github.com/micropython/micropython/issues/6419
This example demonstrates how to load binary fonts dynamically from filesystem:
- Loading different font files for different languages (Chinese, English, Japanese)
- Using filesystem driver to access font files
- Creating labels with custom fonts

try:
script_path = __file__[:__file__.rfind('/')] if __file__.find('/') >= 0 else '.'
except NameError:
script_path = ''
Font Conversion:
To create binary font files, use lv_font_conv tool:

import lvgl as lv
import fs_driver
English font:
lv_font_conv --size 20 --format bin --bpp 1 --font Alibaba-PuHuiTi-Medium.subset.ttf
--range 0x20-0x7f --no-compress -o font-PHT-en-20.bin

lv.init()
Chinese font:
lv_font_conv --size 20 --format bin --bpp 1 --font Alibaba-PuHuiTi-Medium.subset.ttf
--range 0x4e00-0x4e56 --no-compress -o font-PHT-cn-20.bin

# display driver init...
import display_driver_utils # Default implementation. Replace by your driver
driver = display_driver_utils.driver()

# FS driver init.

fs_drv = lv.fs_drv_t()
fs_driver.fs_register(fs_drv, 'S')

'''
 load the font file from filesystem(For me is flash )
 How to convert font files refer here: https://github.com/lvgl/lv_font_conv
 font-PHT-en-20.bin:
   lv_font_conv --size 20 --format bin --bpp 1 --font Alibaba-PuHuiTi-Medium.subset.ttf --range 0x20-0x7f --no-compress -o font-PHT-en-20.bin
 font-PHT-cn-20.bin:
   lv_font_conv --size 20 --format bin --bpp 1 --font Alibaba-PuHuiTi-Medium.subset.ttf --range 0x4e00-0x4e56 --no-compress -o font-PHT-cn-20.bin
 font-PHT-jp-20.bin:
   lv_font_conv --size 20 --format bin --bpp 1 --font Alibaba-PuHuiTi-Medium.subset.ttf --range 0x3042-0x3093 --no-compress -o font-PHT-jp-20.bin
'''
scr = lv.screen_active()
scr.clean()
Japanese font:
lv_font_conv --size 20 --format bin --bpp 1 --font Alibaba-PuHuiTi-Medium.subset.ttf
--range 0x3042-0x3093 --no-compress -o font-PHT-jp-20.bin

myfont_cn = lv.binfont_create("S:%s/font/font-PHT-cn-20.bin" % script_path)
Command line for running on unix port:
MICROPYPATH=./:../lib ../../../ports/unix/micropython -i Dynamic_loading_font_example.py
"""

import usys as sys
sys.path.append('') # See: https://github.com/micropython/micropython/issues/6419

label1 = lv.label(scr)
label1.set_style_text_font(myfont_cn, 0) # set the font
label1.set_text("上中下乎")
label1.align(lv.ALIGN.CENTER, 0, -25)
import lvgl as lv

myfont_en = lv.binfont_create("S:%s/font/font-PHT-en-20.bin" % script_path)
# Initialize LVGL
lv.init()

label2 = lv.label(scr)
label2.set_style_text_font(myfont_en, 0) # set the font
label2.set_text("Hello LVGL!")
label2.align(lv.ALIGN.CENTER, 0, 25)
# Determine script path for font files
try:
script_path = __file__[:__file__.rfind('/')] if __file__.find('/') >= 0 else '.'
except NameError:
script_path = '.'
print("Warning: __file__ not available, using current directory")

# Initialize display driver
try:
import display_driver_utils
driver = display_driver_utils.driver()
except ImportError:
print("Warning: display_driver_utils not available, using default display")

myfont_jp= lv.binfont_create("S:%s/font/font-PHT-jp-20.bin" % script_path)
# Initialize filesystem driver for font loading
try:
import fs_driver
fs_drv = lv.fs_drv_t()
fs_driver.fs_register(fs_drv, 'S')
print("Filesystem driver registered successfully")
except ImportError:
print("Warning: fs_driver not available, fonts may not load correctly")

# Clear the screen and create labels with different fonts
scr = lv.screen_active()
scr.clean()

label3 = lv.label(scr)
label3.set_style_text_font(myfont_jp, 0) # set the font
label3.set_text("こんにちはありがとう")
label3.align(lv.ALIGN.CENTER, 0, 0)
# Load and display Chinese font
try:
myfont_cn = lv.binfont_create("S:%s/font/font-PHT-cn-20.bin" % script_path)
label1 = lv.label(scr)
label1.set_style_text_font(myfont_cn, 0)
label1.set_text("上中下乎") # Chinese text
label1.align(lv.ALIGN.CENTER)
label1.set_y(label1.get_y() - 25)
print("Chinese font loaded successfully")
except Exception as e:
print(f"Failed to load Chinese font: {e}")
label1 = lv.label(scr)
label1.set_text("Chinese font failed")
label1.align(lv.ALIGN.CENTER)
label1.set_y(label1.get_y() - 25)

# Load and display English font
try:
myfont_en = lv.binfont_create("S:%s/font/font-PHT-en-20.bin" % script_path)
label2 = lv.label(scr)
label2.set_style_text_font(myfont_en, 0)
label2.set_text("Hello LVGL!")
label2.align(lv.ALIGN.CENTER)
label2.set_y(label2.get_y() + 25)
print("English font loaded successfully")
except Exception as e:
print(f"Failed to load English font: {e}")
label2 = lv.label(scr)
label2.set_text("Hello LVGL!") # Use default font
label2.align(lv.ALIGN.CENTER)
label2.set_y(label2.get_y() + 25)

# Load and display Japanese font
try:
myfont_jp = lv.binfont_create("S:%s/font/font-PHT-jp-20.bin" % script_path)
label3 = lv.label(scr)
label3.set_style_text_font(myfont_jp, 0)
label3.set_text("こんにちはありがとう") # Japanese text
label3.align(lv.ALIGN.CENTER)
print("Japanese font loaded successfully")
except Exception as e:
print(f"Failed to load Japanese font: {e}")
label3 = lv.label(scr)
label3.set_text("Japanese font failed")
label3.align(lv.ALIGN.CENTER)



Expand Down
163 changes: 163 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
# LVGL MicroPython Examples

This directory contains comprehensive examples demonstrating LVGL (Light and Versatile Graphics Library) usage with MicroPython bindings.

## Quick Start

All examples are compatible with LVGL v9 API. To run an example:

```bash
# Unix port (with SDL for GUI simulation)
cd /path/to/micropython/ports/unix
./build-lvgl/micropython /path/to/examples/example_name.py

# ESP32 port (upload to device)
# Copy the example to your ESP32 and run it
```

## Examples Overview

### Basic Examples

- **`generic-st77xx-with-xpt2046.py`**: Simple button example for ST77XX displays with XPT2046 touch
- **`fb_test.py`**: Linux framebuffer test with basic button and label
- **`example1.py`**: Comprehensive platform-agnostic example with display initialization
- **`example3.py`**: Multi-widget example with sliders, LEDs, buttons, and keyboard

### Advanced Examples

- **`advanced_demo.py`**: Complex multi-platform demo with themes, animations, and charts
- **`custom_widget_example.py`**: Custom widget class creation and theming
- **`uasyncio_example1.py`**: Async/await integration with LVGL using uasyncio

### Specialized Examples

- **`png_example.py`**: PNG image loading and display with drag functionality
- **`Dynamic_loading_font_example.py`**: Loading custom binary fonts for multiple languages

### Migration Guide

- **`LvglV8ToV9MigrationGuide.md`**: Comprehensive guide for migrating from LVGL v8 to v9 API

## Platform Support

Examples support multiple platforms:

- **Unix/Linux**: SDL-based simulation
- **ESP32**: With various display drivers (ILI9341, ST77XX)
- **STM32**: Built-in display support
- **Raspberry Pi Pico**: RP2 platform with SPI displays

## Display Driver Integration

Examples demonstrate integration with various display drivers:

- **ILI9341**: Common SPI TFT display
- **ST77XX**: ST7789/ST7735 family displays
- **SDL**: Cross-platform simulation
- **Framebuffer**: Linux framebuffer support

## Touch Input Support

Touch input examples include:

- **XPT2046**: Resistive touch controller
- **Built-in touch**: Platform-specific touch sensors
- **Mouse simulation**: SDL mouse input

## Key Features Demonstrated

### Widgets
- Buttons, labels, sliders, LEDs
- Text areas and keyboards
- Charts and progress indicators
- Images and custom graphics

### Event Handling
- Button clicks and touch events
- Value change events
- Custom event callbacks
- Async event processing

### Styling and Theming
- Custom styles and themes
- Color and gradient management
- Shadow and border effects
- Layout and alignment

### Advanced Features
- Custom widget creation
- Font loading and text rendering
- Image decoding (PNG)
- Animation systems
- Memory management

## Requirements

### Common Requirements
- MicroPython with LVGL bindings
- Appropriate display driver for your hardware
- Sufficient RAM for graphics operations

### Platform-Specific Requirements

**Unix/Linux:**
- SDL2 development libraries
- X11 or Wayland display server

**ESP32:**
- ESP-IDF or Arduino framework
- SPI display hardware
- Touch controller (optional)

**STM32:**
- STM32 development board with display
- Touch sensor support

## Error Handling

All examples include comprehensive error handling:
- Missing driver detection
- File loading failures
- Platform compatibility checks
- Graceful fallbacks when resources unavailable

## Best Practices

Examples demonstrate LVGL best practices:

1. **Proper initialization**: LVGL init before any operations
2. **Resource management**: Proper cleanup and memory management
3. **Cross-platform compatibility**: Platform detection and appropriate drivers
4. **Error handling**: Graceful failure modes
5. **Code organization**: Clear structure and documentation

## Troubleshooting

### Common Issues

1. **Import errors**: Ensure all required drivers are available
2. **Display not showing**: Check display driver initialization
3. **Touch not working**: Verify touch driver configuration
4. **Memory errors**: Increase heap size or reduce graphics complexity

### Debug Tips

- Enable verbose output in examples for debugging
- Check LVGL configuration (lv_conf.h)
- Verify platform compatibility
- Test with simpler examples first

## Contributing

When adding new examples:

1. Follow existing code style and structure
2. Include comprehensive docstrings
3. Add error handling and platform detection
4. Update this README with new example descriptions
5. Test on multiple platforms when possible

## License

Examples are provided under the same license as the LVGL MicroPython bindings.
8 changes: 5 additions & 3 deletions examples/advanced_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def __init__(self, app, page):

self.label = lv.label(page)
self.label.add_flag(lv.obj.FLAG.IGNORE_LAYOUT)
self.label.align(lv.ALIGN.BOTTOM_LEFT, 0, 0)
self.label.align(lv.ALIGN.BOTTOM_LEFT)

def button_cb(event, name):
self.button_event_count[name] += 1
Expand Down Expand Up @@ -174,7 +174,8 @@ def __init__(self, app, page):

self.style_selector = lv.dropdown(page)
self.style_selector.add_style(ShadowStyle(), lv.PART.MAIN)
self.style_selector.align(lv.ALIGN.OUT_BOTTOM_LEFT, 0, 40)
self.style_selector.align(lv.ALIGN.OUT_BOTTOM_LEFT)
self.style_selector.set_y(self.style_selector.get_y() + 40)
self.style_selector.set_options('\n'.join(x[0] for x in self.styles))
self.style_selector.add_event_cb(self.on_style_selector_changed, lv.EVENT.VALUE_CHANGED, None)

Expand All @@ -183,7 +184,7 @@ def __init__(self, app, page):
self.counter_button.set_size(80,80)
self.counter_label = lv.label(self.counter_button)
self.counter_label.set_text("Count")
self.counter_label.align(lv.ALIGN.CENTER, 0, 0)
self.counter_label.align(lv.ALIGN.CENTER)
self.counter_button.add_event_cb(self.on_counter_button, lv.EVENT.CLICKED, None)
self.counter = 0

Expand Down Expand Up @@ -373,6 +374,7 @@ def init_gui_stm32(self):
self.indev_drv.set_read_cb(lcd.ts_read)

def init_gui_rp2(self):
import machine
import xpt2046
import st77xx
if sys.platform!='rp2': raise ImportError('Only works on the rp2 platform.')
Expand Down
20 changes: 18 additions & 2 deletions examples/custom_widget_example.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@

# This example shows how to create a custom widget and a custom theme
"""
LVGL Custom Widget Example

This example demonstrates how to create a custom widget class and custom theme in LVGL:
- Creating a custom widget class with constructor, destructor, and event callbacks
- Implementing custom drawing for widgets (triangle in this example)
- Creating and applying custom themes
- Proper object lifecycle management

The custom widget draws a triangle that points up when unchecked and down when checked.
"""

##############################################################################
# Initializations
Expand All @@ -9,10 +19,16 @@
sys.path.append('') # See: https://github.com/micropython/micropython/issues/6419

import lvgl as lv
import display_driver

# Initialize LVGL
lv.init()

# Initialize display driver
try:
import display_driver
except ImportError:
print("Warning: display_driver not available, using default display")

##############################################################################
# Helper debug function to print member name
##############################################################################
Expand Down
Loading