2021-08-02 05:59 PM
#include "i2c-lcd.h"
extern I2C_HandleTypeDef hi2c1; // change your handler here accordingly
#define SLAVE_ADDRESS_LCD 0x4E // change this according to ur setup
long ErrCnt_ERR=0;
long ErrCnt_Tout=0;
long ErrCnt_Busy=0;
HAL_StatusTypeDef lcd_send_cmd (char cmd)
{
char data_u, data_l;
uint8_t data_t[4];
data_u = (cmd&0xf0);
data_l = ((cmd<<4)&0xf0);
data_t[0] = data_u|0x0C; //en=1, rs=0
data_t[1] = data_u|0x08; //en=0, rs=0
data_t[2] = data_l|0x0C; //en=1, rs=0
data_t[3] = data_l|0x08; //en=0, rs=0
return HAL_I2C_Master_Transmit (&hi2c1, SLAVE_ADDRESS_LCD,(uint8_t *) data_t, 4, 100);
}
HAL_StatusTypeDef lcd_send_data (char data)
{
char data_u, data_l;
uint8_t data_t[4];
data_u = (data&0xf0);
data_l = ((data<<4)&0xf0);
data_t[0] = data_u|0x0D; //en=1, rs=1
data_t[1] = data_u|0x09; //en=0, rs=1
data_t[2] = data_l|0x0D; //en=1, rs=1
data_t[3] = data_l|0x09; //en=0, rs=1
return HAL_I2C_Master_Transmit (&hi2c1, SLAVE_ADDRESS_LCD,(uint8_t *) data_t, 4, 100);
}
void LCDErrEscape(HAL_StatusTypeDef er_type)
{
lcd_init();
if (er_type==HAL_ERROR) ErrCnt_ERR++;
if (er_type==HAL_TIMEOUT) ErrCnt_Tout++;
if (er_type==HAL_BUSY) ErrCnt_Busy++;
HAL_Delay(100);
}
void lcd_clear (void)
{
HAL_StatusTypeDef err;
//err=lcd_send_cmd (0x00);
err=lcd_send_cmd (0x01);
if (err!=HAL_OK) LCDErrEscape(err);
for (int i=0; i<100; i++)
{
err=lcd_send_data (' ');
if (err!=HAL_OK)
{
LCDErrEscape(err);
//HAL_Delay(100);
break;
}
}
}
void lcd_init (void)
{
// 4 bit initialisation
HAL_Delay(50); // wait for >40ms
lcd_send_cmd (0x30);
HAL_Delay(5); // wait for >4.1ms
lcd_send_cmd (0x30);
HAL_Delay(1); // wait for >100us
lcd_send_cmd (0x30);
HAL_Delay(10);
lcd_send_cmd (0x20); // 4bit mode
HAL_Delay(10);
// dislay initialisation
lcd_send_cmd (0x28); // Function set --> DL=0 (4 bit mode), N = 1 (2 line display) F = 0 (5x8 characters)
HAL_Delay(1);
lcd_send_cmd (0x08); //Display on/off control --> D=0,C=0, B=0 ---> display off
HAL_Delay(1);
lcd_send_cmd (0x01); // clear display
HAL_Delay(1);
HAL_Delay(1);
lcd_send_cmd (0x06); //Entry mode set --> I/D = 1 (increment cursor) & S = 0 (no shift)
HAL_Delay(1);
lcd_send_cmd (0x0C); //Display on/off control --> D = 1, C and B = 0. (Cursor and blink, last two bits)
}
void lcd_send_string(char* str)
{
HAL_StatusTypeDef err;
for (int i = 0; *str && i<20; i++) //LCD limit 20char
{
err=lcd_send_data(*str++);
if (err !=HAL_OK)
{
LCDErrEscape(err);
return ;
}
}
}
void LCD_Data_Location(uint8_t x, uint8_t y)
{
HAL_StatusTypeDef err;
if(y == 0){
//lcd_send_cmd ((0x80|0x00)+x);//Cmd_Write(0x80 + x);
err=lcd_send_cmd ((0x80|0x00)+x);
if (err !=HAL_OK)
{
LCDErrEscape(err);
}
}
else if(y == 1){
err=lcd_send_cmd ((0x80|0x40)+x);
if (err !=HAL_OK)
{
LCDErrEscape(err);
//return false;
}
}
else if(y == 2){
err=lcd_send_cmd ((0x80|0x14)+x);
if (err !=HAL_OK)
{
LCDErrEscape(err);
}
}
else if(y == 3){
err=lcd_send_cmd ((0x80|0x54)+x);
if (err !=HAL_OK)
{
LCDErrEscape(err);
}
}
}