Skip to content
Closed
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
20 changes: 13 additions & 7 deletions main/lcd.c
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,24 @@ static i2c_master_dev_handle_t i2c_device_handle = NULL;
static i2c_master_bus_handle_t i2c_bus_handle = NULL;
static uint8_t lcd_backlight_status = LCD_BACKLIGHT;

// Helper function to wait for a period with higher granularity
// than a tick while LCD completes its commands
static void wait_lcd_cycles(uint16_t cycles) {
// if esp32 is 100x faster than the lcd clock speed, then this loop runs 100 * cycles
for( volatile int i = 0; i < (configCPU_CLOCK_HZ/I2C_MASTER_FREQ_HZ) * cycles; i++ ) {
__asm__( "nop" ); // Do nothing, just waste time counting
}
}

// Helper function to toggle the enable bit
static esp_err_t i2c_transmit_with_enable_toggle(uint8_t data) {
uint8_t data_with_enable = data | LCD_ENABLE;
ESP_ERROR_CHECK(i2c_master_transmit(i2c_device_handle, &data_with_enable, 1, -1));
vTaskDelay(pdMS_TO_TICKS(1));
wait_lcd_cycles(2);

data_with_enable &= ~LCD_ENABLE;
ESP_ERROR_CHECK(i2c_master_transmit(i2c_device_handle, &data_with_enable, 1, -1));
vTaskDelay(pdMS_TO_TICKS(1));
wait_lcd_cycles(2);

return ESP_OK;
}
Expand All @@ -26,7 +35,6 @@ static esp_err_t i2c_send_byte_on_4bits(uint8_t data, uint8_t rs) {
};
ESP_ERROR_CHECK(i2c_transmit_with_enable_toggle(nibbles[0]));
ESP_ERROR_CHECK(i2c_transmit_with_enable_toggle(nibbles[1]));
vTaskDelay(pdMS_TO_TICKS(1));
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

with the wait inside i2c_transmit_with_enable_toggle, this wait is not really doing anything.

ESP_LOGI(TAG, "I2C device data sent: 0x%02X", data);

return ESP_OK;
Expand All @@ -52,7 +60,7 @@ void i2c_master_init(void) {
};
ESP_ERROR_CHECK(i2c_master_bus_add_device(i2c_bus_handle, &i2c_device_config, &i2c_device_handle));
ESP_LOGI(TAG, "I2C device added");
vTaskDelay(pdMS_TO_TICKS(50)); // Wait for LCD to power up
vTaskDelay(pdMS_TO_TICKS(50) + 1); // Wait for LCD to power up
ESP_LOGI(TAG, "I2C device initialized");
}

Expand All @@ -78,12 +86,10 @@ void lcd_init(void) {

for (uint8_t i = 0; i < sizeof(init_8bit_commands); i++) {
ESP_ERROR_CHECK(i2c_transmit_with_enable_toggle(init_8bit_commands[i]));
vTaskDelay(pdMS_TO_TICKS(5));
}

for (uint8_t i = 0; i < sizeof(init_commands); i++) {
ESP_ERROR_CHECK(i2c_send_byte_on_4bits(init_commands[i], LCD_RS_CMD));
vTaskDelay(pdMS_TO_TICKS(5));
}
}

Expand All @@ -108,7 +114,7 @@ void lcd_write_string(const char *str) {
void lcd_clear(void) {
uint8_t data = 0b00000001;
ESP_ERROR_CHECK(i2c_send_byte_on_4bits(data, LCD_RS_CMD));
vTaskDelay(pdMS_TO_TICKS(2));
wait_lcd_cycles(310);
}

// Control the LCD backlight
Expand Down