76 lines
2.7 KiB
Python
76 lines
2.7 KiB
Python
import machine
|
|
import st7789py as st7789
|
|
from config import CURRENT_CONFIG
|
|
|
|
class Display:
|
|
def __init__(self):
|
|
self.tft = None
|
|
self.width = 240
|
|
self.height = 240
|
|
self._init_display()
|
|
|
|
def _init_display(self):
|
|
print(">>> Initializing Display...")
|
|
try:
|
|
pins = CURRENT_CONFIG.pins
|
|
spi = machine.SPI(2, baudrate=40000000, polarity=1, phase=1,
|
|
sck=machine.Pin(pins['sck']), mosi=machine.Pin(pins['mosi']))
|
|
|
|
cs_pin = pins.get('cs')
|
|
cs = machine.Pin(cs_pin, machine.Pin.OUT) if cs_pin is not None else None
|
|
|
|
rst_pin = pins.get('rst')
|
|
dc_pin = pins.get('dc')
|
|
|
|
self.tft = st7789.ST7789(spi, self.width, self.height,
|
|
reset=machine.Pin(rst_pin, machine.Pin.OUT) if rst_pin else None,
|
|
dc=machine.Pin(dc_pin, machine.Pin.OUT) if dc_pin else None,
|
|
cs=cs,
|
|
backlight=None)
|
|
self.tft.init()
|
|
self.tft.fill(st7789.BLUE)
|
|
except Exception as e:
|
|
print(f"Display error: {e}")
|
|
self.tft = None
|
|
|
|
def fill(self, color):
|
|
if self.tft:
|
|
self.tft.fill(color)
|
|
|
|
def fill_rect(self, x, y, w, h, color):
|
|
if self.tft:
|
|
self.tft.fill_rect(x, y, w, h, color)
|
|
|
|
def init_ui(self):
|
|
"""初始化 UI 背景"""
|
|
if self.tft:
|
|
self.tft.fill(st7789.BLACK)
|
|
self.tft.fill_rect(0, 0, 240, 30, st7789.WHITE)
|
|
|
|
def update_audio_bar(self, bar_height, last_bar_height):
|
|
"""更新音频可视化的柱状图"""
|
|
if not self.tft: return last_bar_height
|
|
|
|
# 确定当前颜色
|
|
color = st7789.GREEN
|
|
if bar_height > 50: color = st7789.YELLOW
|
|
if bar_height > 100: color = st7789.RED
|
|
|
|
# 确定上一次颜色
|
|
last_color = st7789.GREEN
|
|
if last_bar_height > 50: last_color = st7789.YELLOW
|
|
if last_bar_height > 100: last_color = st7789.RED
|
|
|
|
# 1. 如果变矮了,清除顶部多余部分
|
|
if bar_height < last_bar_height:
|
|
self.tft.fill_rect(100, 240 - last_bar_height, 40, last_bar_height - bar_height, st7789.BLACK)
|
|
|
|
# 2. 如果颜色变了,必须重绘整个条
|
|
if color != last_color:
|
|
self.tft.fill_rect(100, 240 - bar_height, 40, bar_height, color)
|
|
# 3. 如果颜色没变且变高了,只绘新增部分
|
|
elif bar_height > last_bar_height:
|
|
self.tft.fill_rect(100, 240 - bar_height, 40, bar_height - last_bar_height, color)
|
|
|
|
return bar_height
|