#include "LCD16x2_I2C.h"
#include <stdio.h>

/* Generated by CubeMX in main.c */
extern I2C_HandleTypeDef hi2c1;

/* PCF8574 -> HD44780 wiring on the common adapter boards:
 * P0 = RS, P1 = R/W, P2 = E, P3 = backlight, P4-P7 = D4-D7 */
#define LCD_RS 0x01
#define LCD_EN 0x04
#define LCD_BL 0x08

/* Send the upper 4 bits of `nibble` with one pulse on E */
static void lcd_write4(uint8_t nibble, uint8_t rs)
{
    uint8_t data   = (nibble & 0xF0) | LCD_BL | rs;
    uint8_t buf[2] = { data | LCD_EN, data };   /* E high, then E low latches */

    HAL_I2C_Master_Transmit(&hi2c1, LCD_I2C_ADDR, buf, 2, 100);
}

/* 4-bit mode: a byte is sent as two nibbles, high first */
static void lcd_send(uint8_t byte, uint8_t rs)
{
    lcd_write4(byte & 0xF0, rs);
    lcd_write4(byte << 4, rs);
}

static void lcd_command(uint8_t cmd)
{
    lcd_send(cmd, 0);
}

void LCD_init(void)
{
    HAL_Delay(50);              /* wait for the LCD to power up */

    /* Reset sequence from the HD44780 datasheet, then switch to 4-bit */
    lcd_write4(0x30, 0);
    HAL_Delay(5);
    lcd_write4(0x30, 0);
    HAL_Delay(1);
    lcd_write4(0x30, 0);
    HAL_Delay(1);
    lcd_write4(0x20, 0);
    HAL_Delay(1);

    lcd_command(0x28);          /* 4-bit, 2 lines, 5x8 font  */
    lcd_command(0x08);          /* display off               */
    LCD_clear();
    lcd_command(0x06);          /* cursor moves right        */
    lcd_command(0x0C);          /* display on, cursor hidden */
}

void LCD_clear(void)
{
    lcd_command(0x01);
    HAL_Delay(2);               /* clear takes 1.52 ms */
}

void LCD_setCursor(uint8_t row, uint8_t col)
{
    uint8_t address = (row == 0 ? 0x00 : 0x40) + col;

    lcd_command(0x80 | address);
}

void LCD_displayText(char *text)
{
    while (*text)
    {
        lcd_send((uint8_t)*text++, LCD_RS);
    }
}

void LCD_displayInt(int number)
{
    char numStr[12];

    snprintf(numStr, sizeof(numStr), "%d", number);
    LCD_displayText(numStr);
}
