OLED显示屏上的时间与温度
在本示例中,我使用了SSD1306 OLED显示屏(I²C接口)来显示当前时间和来自Home Assistant的两个不同温度值。
ESPHome支持多种不同类型的显示屏。这里使用的显示屏是1.3英寸,128x64单色像素(SH1106 128x64)。
硬件很简单!只需要四个连接:
VCC- 电源(我的显示屏可以使用3.3V或5V)GND- 地线SDA- 串行数据SCL- 串行时钟
WARNING
如果使用5V,请确保您的显示屏支持5V。
从Home Assistant获取时间以同步板载实时时钟。
time: - platform: homeassistant id: esptime接下来,我们要从Home Assistant导入一个温度传感器和天气预报。
我将它们命名为 inside_temperature 和 outside_temperature。稍后您将使用这些引用。
通过为传感器添加 internal: true,它们将不会被发布回Home Assistant。
sensor: - platform: homeassistant id: inside_temperature entity_id: REPLACEME internal: true
- platform: homeassistant id: outside_temperature entity_id: REPLACEME internal: true
text_sensor: - platform: homeassistant id: outside_temperature_unit entity_id: REPLACEME attribute: temperature_unit internal: true- 使用TrueType字体。如果您曾在微控制器上使用过字体,您会爱上这个功能!
- 将字体文件保存在
/config/esphome文件夹中,即ESPHome配置存储的位置。 .ttf后缀必须是小写,并且与您的文件名匹配。- 选择小尺寸字体时可能有点棘手,需要反复尝试才能看起来美观。欢迎实验并在下方评论中分享您的发现!
font: - file: 'slkscr.ttf' id: small size: 8
- file: 'BebasNeue-Regular.ttf' id: medium size: 48
- file: 'arial.ttf' id: large size: 14- (可选)您也可以使用
gfonts://方案直接使用Google字体,无需包含字体文件。 - 更多信息请参阅字体文档。
font: - file: "gfonts://Silkscreen" id: small size: 10 - file: "gfonts://Roboto" id: large size: 24 - file: "gfonts://Silkscreen" id: medium size: 15现在设置与显示屏的通信,并开始用实时数据填充屏幕!
我的硬件配置中没有使用 reset_pin,因为我的显示屏没有暴露该引脚。
请注意您的 address 和 model 可能不同,可以使用扫描选项来查找显示屏的地址。
i2c: sda: GPIOXX scl: GPIOXX scan: false # manually setting the frequency to a higher rate may avoid long component updates # frequency: 300kHz
display: - platform: ssd1306_i2c model: "SH1106 128x64" reset_pin: GPIOXX address: 0x3C lambda: |- it.printf(0, 0, id(small), TextAlign::TOP_LEFT, "Time and"); it.printf(0, 12, id(small), TextAlign::TOP_LEFT, "Temperature");
// Print time in HH:MM format it.strftime(0, 60, id(large), TextAlign::BASELINE_LEFT, "%H:%M", id(esptime).now());
// Print inside temperature (from homeassistant sensor) if (id(inside_temperature).has_state()) { it.printf(127, 23, id(medium), TextAlign::TOP_RIGHT , "%.1f", id(inside_temperature).state); }
// Print outside temperature (from homeassistant weather) if (id(outside_temperature).has_state()) { it.printf(127, 60, id(medium), TextAlign::BASELINE_RIGHT , "%.1f%s", id(outside_temperature).state, id(outside_temperature_unit).state.c_str()); }-
文本对齐可以使用不同的参考点,例如
TOP_RIGHT或BASELINE_LEFT,这些都定义在 API 参考:display_buffer.h 中。 -
传感器上的
has_state()属性非常有用,因为从Home Assistant获取数据可能需要几秒钟,您可能不希望显示Nan -
请参考渲染引擎显示渲染引擎了解更多功能(它还可以绘制线条和圆形!)
添加基于文本的传感器
Section titled “添加基于文本的传感器”下面是一个示例,将顶部的”时间与温度”打印替换为Home Assistant中报警组件的报警状态。
text_sensor: - platform: homeassistant entity_id: alarm_control_panel.my_alarm_system name: "Alarm State" id: alarm_state
display: - platform: ssd1306_i2c model: "SH1106 128x64" reset_pin: GPIOXX address: 0x3C lambda: |- // Print "Alarm State: <state>" in top center it.printf(64, 0, id(small), TextAlign::TOP_CENTER, "Alarm State: %s", id(alarm_state).state.c_str());