Hello, I made a temperature display using ESP8622+SH1106. Below, I’m including the code. Everything works fine, but the display is too bright at night, and I would like to reduce its contrast to 10%, while during the day I would like to set it to 50%. I’ve tried various methods but couldn’t get it to work. Does anyone know a way to do this? Is it even possible?
time:
- platform: sntp
id: time_sntp
sensor:
- platform: homeassistant
id: temperatura_ogrod
entity_id: sensor.sonoffch4pror2_temperatura_na_zewntrz
internal: true
i2c:
sda: GPIO04
scl: GPIO05
frequency: 400kHz
scan: False
font:
- file: 'BebasNeue-Regular.ttf'
id: font1
size: 40
- file: 'BebasNeue-Regular.ttf'
id: font2
size: 89
display:
- platform: ssd1306_i2c
id: wyswietlacz_OLED
model: "SH1106 128x64"
address: 0x3C
contrast: 10%
update_interval: 30s
lambda: |-
if (id(temperatura_ogrod).has_state()) {
float temp = id(temperatura_ogrod).state;
int temp_integer = (int)temp;
int temp_fraction = (int)round((temp - temp_integer) * 10);
char temp_integer_str[4]; // To store the integer part.
char temp_fraction_str[14]; // To store the fractional part and the degree symbol.
snprintf(temp_integer_str, sizeof(temp_integer_str), "%d", temp_integer);
snprintf(temp_fraction_str, sizeof(temp_fraction_str), ".%d°", abs(temp_fraction)); // Using the abs() function to remove the minus sign.
// Character width in pixels for BebasNeue-Regular.ttf at size 89.
int char_width = 24;
// Calculate the width of the integer part.
int width_integer = strlen(temp_integer_str) * char_width + 10;
// Positions from which the integer and fractional parts begin.
int start_x_integer = 0;
int start_x_fraction = 0;
// Conditions for different lengths of the integer part of the text.
if (strlen(temp_integer_str) == 1) {
// For single-digit positive temperatures.
start_x_integer = 47;
start_x_fraction = start_x_integer + width_integer;
} else if (strlen(temp_integer_str) == 2) {
// For single-digit negative temperatures and double-digit positive temperatures.
// Special position for negative single-digit temperatures.
if (temp_integer < 0) {
start_x_integer = 20;
start_x_fraction = start_x_integer + width_integer;
} else {
start_x_integer = 20;
start_x_fraction = start_x_integer + width_integer + 12;
}
} else if (strlen(temp_integer_str) == 3) {
// For double-digit negative temperatures.
start_x_integer = -5;
start_x_fraction = start_x_integer + width_integer + 12;
}
// Displaying temperatures in the correct positions.
it.printf(start_x_integer, 90, id(font2), TextAlign::BOTTOM_LEFT, "%s", temp_integer_str); // Integer part
it.printf(start_x_fraction, 60, id(font1), TextAlign::BASELINE_LEFT, "%s", temp_fraction_str); // Fractional part.
} else {
it.printf(64, 64, id(font2), TextAlign::BASELINE_CENTER, "--");
}