Base class for LCDs

Hi all,

Wouldn't it be advantageous to have a base class for all the different LCD libraries to inherit from? I'm thinking of LiquidCrystal and all the versions that are basically the same class but with different send methods to use I2C or SPI or whatever. It would certainly make it simpler to write a library that uses an LCD and then let the user pass in a pointer to that base class so the end user can decide whether to have a parallel or I2C or Serial or whatever type of LCD and can use his own library.

I'm willing to do all the heavy lifting on it. But I wanted to see if you all thought it would be worthwhile before I start coding. It's only really worth it if we think we can get the standard LiquidCrystal library to inherit from it so that it works across standard installations. I don't think anything has to change, it just needs to inherit from a base class that implements most of its functionality. Then the individual implementations are just defining a send() method which I guess is pure virtual in the base class.

Here's an example of where it could have helped for the user to call his own LCD constructor in setup and just pass my library a pointer to something that has all the basic functionality of an LCD without any worry about how it is actually connected.

I guess begin, send, and the constructor have to be implemented separately for each type of LCD. Aside from that, all the functions that the user actually touches are either identical and call send or they are inherited from Print anyway.

This compiles. I wonder if anyone would be so kind as to see if it works for me.

You’d have to replace your local copy of LiquidCrystal and add a folder for the LCD_BaseClass to libraries in your Arduino installation. Be sure to back up the old stuff.

LCD_BaseClass.h

#ifndef LCD_BaseClass_h
#define LCD_BaseClass_h

#include <inttypes.h>
#include "Print.h"
#include "Arduino.h"

// commands
#define LCD_CLEARDISPLAY 0x01
#define LCD_RETURNHOME 0x02
#define LCD_ENTRYMODESET 0x04
#define LCD_DISPLAYCONTROL 0x08
#define LCD_CURSORSHIFT 0x10
#define LCD_FUNCTIONSET 0x20
#define LCD_SETCGRAMADDR 0x40
#define LCD_SETDDRAMADDR 0x80

// flags for display entry mode
#define LCD_ENTRYRIGHT 0x00
#define LCD_ENTRYLEFT 0x02
#define LCD_ENTRYSHIFTINCREMENT 0x01
#define LCD_ENTRYSHIFTDECREMENT 0x00

// flags for display on/off control
#define LCD_DISPLAYON 0x04
#define LCD_DISPLAYOFF 0x00
#define LCD_CURSORON 0x02
#define LCD_CURSOROFF 0x00
#define LCD_BLINKON 0x01
#define LCD_BLINKOFF 0x00

// flags for display/cursor shift
#define LCD_DISPLAYMOVE 0x08
#define LCD_CURSORMOVE 0x00
#define LCD_MOVERIGHT 0x04
#define LCD_MOVELEFT 0x00

// flags for function set
#define LCD_8BITMODE 0x10
#define LCD_4BITMODE 0x00
#define LCD_2LINE 0x08
#define LCD_1LINE 0x00
#define LCD_5x10DOTS 0x04
#define LCD_5x8DOTS 0x00

class LCD_BaseClass : public Print {
public:
	LCD_BaseClass();

  void clear();
  void home();

  void noDisplay();
  void display();
  void noBlink();
  void blink();
  void noCursor();
  void cursor();
  void scrollDisplayLeft();
  void scrollDisplayRight();
  void leftToRight();
  void rightToLeft();
  void autoscroll();
  void noAutoscroll();

  void setRowOffsets(uint8_t cols, uint8_t lines);
  void setRowOffsets(int row1, int row2, int row3, int row4);
  void createChar(uint8_t, uint8_t[]);
  void setCursor(uint8_t, uint8_t);
  virtual size_t write(uint8_t);
  void command(uint8_t);

  using Print::write;
protected:
  virtual void send(uint8_t, uint8_t);

  uint8_t _displayfunction;
  uint8_t _displaycontrol;
  uint8_t _displaymode;

//  uint8_t _initialized;

  uint8_t _numlines;
  uint8_t _row_offsets[4];
};

#endif

LCD_BaseClass.cpp

#include "LCD_BaseClass.h"

#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "Arduino.h"

// When the display powers up, it is configured as follows:
//
// 1. Display clear
// 2. Function set:
//    DL = 1; 8-bit interface data
//    N = 0; 1-line display
//    F = 0; 5x8 dot character font
// 3. Display on/off control:
//    D = 0; Display off
//    C = 0; Cursor off
//    B = 0; Blinking off
// 4. Entry mode set:
//    I/D = 1; Increment by 1
//    S = 0; No shift
//
// Note, however, that resetting the Arduino doesn't reset the LCD, so we
// can't assume that its in that state when a sketch starts (and the
// LCD_BaseClass constructor is called).

LCD_BaseClass::LCD_BaseClass(){

}

void LCD_BaseClass::setRowOffsets(uint8_t cols, uint8_t lines){
	  _numlines = lines;
	  setRowOffsets(0x00, 0x40, 0x00 + cols, 0x40 + cols);
}


void LCD_BaseClass::setRowOffsets(int row0, int row1, int row2, int row3)
{
  _row_offsets[0] = row0;
  _row_offsets[1] = row1;
  _row_offsets[2] = row2;
  _row_offsets[3] = row3;
}

/********** high level commands, for the user! */
void LCD_BaseClass::clear()
{
  command(LCD_CLEARDISPLAY);  // clear display, set cursor position to zero
  delayMicroseconds(2000);  // this command takes a long time!
}

void LCD_BaseClass::home()
{
  command(LCD_RETURNHOME);  // set cursor position to zero
  delayMicroseconds(2000);  // this command takes a long time!
}

void LCD_BaseClass::setCursor(uint8_t col, uint8_t row)
{
  const size_t max_lines = sizeof(_row_offsets) / sizeof(*_row_offsets);
  if ( row >= max_lines ) {
    row = max_lines - 1;    // we count rows starting w/0
  }
  if ( row >= _numlines ) {
    row = _numlines - 1;    // we count rows starting w/0
  }

  command(LCD_SETDDRAMADDR | (col + _row_offsets[row]));
}

// Turn the display on/off (quickly)
void LCD_BaseClass::noDisplay() {
  _displaycontrol &= ~LCD_DISPLAYON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}
void LCD_BaseClass::display() {
  _displaycontrol |= LCD_DISPLAYON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}

// Turns the underline cursor on/off
void LCD_BaseClass::noCursor() {
  _displaycontrol &= ~LCD_CURSORON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}
void LCD_BaseClass::cursor() {
  _displaycontrol |= LCD_CURSORON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}

// Turn on and off the blinking cursor
void LCD_BaseClass::noBlink() {
  _displaycontrol &= ~LCD_BLINKON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}
void LCD_BaseClass::blink() {
  _displaycontrol |= LCD_BLINKON;
  command(LCD_DISPLAYCONTROL | _displaycontrol);
}

// These commands scroll the display without changing the RAM
void LCD_BaseClass::scrollDisplayLeft(void) {
  command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT);
}
void LCD_BaseClass::scrollDisplayRight(void) {
  command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT);
}

// This is for text that flows Left to Right
void LCD_BaseClass::leftToRight(void) {
  _displaymode |= LCD_ENTRYLEFT;
  command(LCD_ENTRYMODESET | _displaymode);
}

// This is for text that flows Right to Left
void LCD_BaseClass::rightToLeft(void) {
  _displaymode &= ~LCD_ENTRYLEFT;
  command(LCD_ENTRYMODESET | _displaymode);
}

// This will 'right justify' text from the cursor
void LCD_BaseClass::autoscroll(void) {
  _displaymode |= LCD_ENTRYSHIFTINCREMENT;
  command(LCD_ENTRYMODESET | _displaymode);
}

// This will 'left justify' text from the cursor
void LCD_BaseClass::noAutoscroll(void) {
  _displaymode &= ~LCD_ENTRYSHIFTINCREMENT;
  command(LCD_ENTRYMODESET | _displaymode);
}

// Allows us to fill the first 8 CGRAM locations
// with custom characters
void LCD_BaseClass::createChar(uint8_t location, uint8_t charmap[]) {
  location &= 0x7; // we only have 8 locations 0-7
  command(LCD_SETCGRAMADDR | (location << 3));
  for (int i=0; i<8; i++) {
    write(charmap[i]);
  }
}

/*********** mid level commands, for sending data/cmds */

inline void LCD_BaseClass::command(uint8_t value) {
  send(value, LOW);
}

inline size_t LCD_BaseClass::write(uint8_t value) {
  send(value, HIGH);
  return 1; // assume sucess
}

LiquidCrystal becomes

LiquidCrystal.h

#ifndef LiquidCrystal_h
#define LiquidCrystal_h

#include <inttypes.h>
#include "LCD_BaseClass.h"

class LiquidCrystal : public LCD_BaseClass {
public:
  LiquidCrystal(uint8_t rs, uint8_t enable,
		uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
		uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
		uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
		uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
		uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
  LiquidCrystal(uint8_t rs, uint8_t enable,
		uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);

  void init(uint8_t fourbitmode, uint8_t rs, uint8_t rw, uint8_t enable,
	    uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
	    uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
    
  void begin(uint8_t cols, uint8_t rows, uint8_t charsize = LCD_5x8DOTS);

  
  using Print::write;
private:
  void send(uint8_t, uint8_t);
  void write4bits(uint8_t);
  void write8bits(uint8_t);
  void pulseEnable();

  uint8_t _rs_pin; // LOW: command.  HIGH: character.
  uint8_t _rw_pin; // LOW: write to LCD.  HIGH: read from LCD.
  uint8_t _enable_pin; // activated by a HIGH pulse.
  uint8_t _data_pins[8];
};

#endif

LiquidCrystal.cpp

#include "LiquidCrystal.h"

#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "Arduino.h"

// When the display powers up, it is configured as follows:
//
// 1. Display clear
// 2. Function set: 
//    DL = 1; 8-bit interface data 
//    N = 0; 1-line display 
//    F = 0; 5x8 dot character font 
// 3. Display on/off control: 
//    D = 0; Display off 
//    C = 0; Cursor off 
//    B = 0; Blinking off 
// 4. Entry mode set: 
//    I/D = 1; Increment by 1 
//    S = 0; No shift 
//
// Note, however, that resetting the Arduino doesn't reset the LCD, so we
// can't assume that its in that state when a sketch starts (and the
// LiquidCrystal constructor is called).

LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
			     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
			     uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)
{
  init(0, rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7);
}

LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t enable,
			     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
			     uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)
{
  init(0, rs, 255, enable, d0, d1, d2, d3, d4, d5, d6, d7);
}

LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
			     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)
{
  init(1, rs, rw, enable, d0, d1, d2, d3, 0, 0, 0, 0);
}

LiquidCrystal::LiquidCrystal(uint8_t rs,  uint8_t enable,
			     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)
{
  init(1, rs, 255, enable, d0, d1, d2, d3, 0, 0, 0, 0);
}

void LiquidCrystal::init(uint8_t fourbitmode, uint8_t rs, uint8_t rw, uint8_t enable,
			 uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
			 uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)
{
  _rs_pin = rs;
  _rw_pin = rw;
  _enable_pin = enable;
  
  _data_pins[0] = d0;
  _data_pins[1] = d1;
  _data_pins[2] = d2;
  _data_pins[3] = d3; 
  _data_pins[4] = d4;
  _data_pins[5] = d5;
  _data_pins[6] = d6;
  _data_pins[7] = d7; 

  if (fourbitmode)
    _displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_5x8DOTS;
  else 
    _displayfunction = LCD_8BITMODE | LCD_1LINE | LCD_5x8DOTS;
  
//  begin(16, 1);    // Shouldn't call begin from constructor
}

void LiquidCrystal::begin(uint8_t cols, uint8_t lines, uint8_t dotsize) {

  setRowOffsets(cols, lines);

  // for some 1 line displays you can select a 10 pixel high font
  if ((dotsize != LCD_5x8DOTS) && (lines == 1)) {
    _displayfunction |= LCD_5x10DOTS;
  }

  pinMode(_rs_pin, OUTPUT);
  // we can save 1 pin by not using RW. Indicate by passing 255 instead of pin#
  if (_rw_pin != 255) { 
    pinMode(_rw_pin, OUTPUT);
  }
  pinMode(_enable_pin, OUTPUT);
  
  // Do these once, instead of every time a character is drawn for speed reasons.
  for (int i=0; i<((_displayfunction & LCD_8BITMODE) ? 8 : 4); ++i)
  {
    pinMode(_data_pins[i], OUTPUT);
   } 

  // SEE PAGE 45/46 FOR INITIALIZATION SPECIFICATION!
  // according to datasheet, we need at least 40ms after power rises above 2.7V
  // before sending commands. Arduino can turn on way before 4.5V so we'll wait 50
  delayMicroseconds(50000); 
  // Now we pull both RS and R/W low to begin commands
  digitalWrite(_rs_pin, LOW);
  digitalWrite(_enable_pin, LOW);
  if (_rw_pin != 255) { 
    digitalWrite(_rw_pin, LOW);
  }
  
  //put the LCD into 4 bit or 8 bit mode
  if (! (_displayfunction & LCD_8BITMODE)) {
    // this is according to the hitachi HD44780 datasheet
    // figure 24, pg 46

    // we start in 8bit mode, try to set 4 bit mode
    write4bits(0x03);
    delayMicroseconds(4500); // wait min 4.1ms

    // second try
    write4bits(0x03);
    delayMicroseconds(4500); // wait min 4.1ms
    
    // third go!
    write4bits(0x03); 
    delayMicroseconds(150);

    // finally, set to 4-bit interface
    write4bits(0x02); 
  } else {
    // this is according to the hitachi HD44780 datasheet
    // page 45 figure 23

    // Send function set command sequence
    command(LCD_FUNCTIONSET | _displayfunction);
    delayMicroseconds(4500);  // wait more than 4.1ms

    // second try
    command(LCD_FUNCTIONSET | _displayfunction);
    delayMicroseconds(150);

    // third go
    command(LCD_FUNCTIONSET | _displayfunction);
  }

  // finally, set # lines, font size, etc.
  command(LCD_FUNCTIONSET | _displayfunction);  

  // turn the display on with no cursor or blinking default
  _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF;  
  display();

  // clear it off
  clear();

  // Initialize to default text direction (for romance languages)
  _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT;
  // set the entry mode
  command(LCD_ENTRYMODESET | _displaymode);

}



/************ low level data pushing commands **********/

// write either command or data, with automatic 4/8-bit selection
void LiquidCrystal::send(uint8_t value, uint8_t mode) {
  digitalWrite(_rs_pin, mode);

  // if there is a RW pin indicated, set it low to Write
  if (_rw_pin != 255) { 
    digitalWrite(_rw_pin, LOW);
  }
  
  if (_displayfunction & LCD_8BITMODE) {
    write8bits(value); 
  } else {
    write4bits(value>>4);
    write4bits(value);
  }
}

void LiquidCrystal::pulseEnable(void) {
  digitalWrite(_enable_pin, LOW);
  delayMicroseconds(1);    
  digitalWrite(_enable_pin, HIGH);
  delayMicroseconds(1);    // enable pulse must be >450ns
  digitalWrite(_enable_pin, LOW);
  delayMicroseconds(100);   // commands need > 37us to settle
}

void LiquidCrystal::write4bits(uint8_t value) {
  for (int i = 0; i < 4; i++) {
    digitalWrite(_data_pins[i], (value >> i) & 0x01);
  }

  pulseEnable();
}

void LiquidCrystal::write8bits(uint8_t value) {
  for (int i = 0; i < 8; i++) {
    digitalWrite(_data_pins[i], (value >> i) & 0x01);
  }
  
  pulseEnable();
}

If anyone has an Arduino hooked up to use the normal LiquidCrystal library and knows enough to sub in this library for the built in one I’d appreciate a test run. It would be a while before I could set that up. Just run through the built in examples in LiquidCrystal, substituting these files in the src folder. You’ll also have to add a folder to libraries with the LCD_BaseClass stuff in it.

Is it possible for you to provide a list of the LCD types that you would consider to be included in the class? I’d be willing to set up a test, but the only LCD I have is a generic 16x2.

LiquidCrystal_I2C now looks like: (Note LiquidCrystal_I2C already had some extra functionality and it retains that.)

LiquidCrystal_I2C.h

#ifndef FDB_LIQUID_CRYSTAL_I2C_H
#define FDB_LIQUID_CRYSTAL_I2C_H

#include <inttypes.h>
#include <Print.h>
#include <LCD_BaseClass.h>

// flags for backlight control
#define LCD_BACKLIGHT 0x08
#define LCD_NOBACKLIGHT 0x00

#define En B00000100  // Enable bit
#define Rw B00000010  // Read/Write bit
#define Rs B00000001  // Register select bit

/**
 * This is the driver for the Liquid Crystal LCD displays that use the I2C bus.
 *
 * After creating an instance of this class, first call begin() before anything else.
 * The backlight is on by default, since that is the most likely operating mode in
 * most cases.
 */
class LiquidCrystal_I2C : public LCD_BaseClass {
public:
 /**
 * Constructor
 *
 * @param lcd_addr I2C slave address of the LCD display. Most likely printed on the
 * LCD circuit board, or look in the supplied LCD documentation.
 * @param lcd_cols Number of columns your LCD display has.
 * @param lcd_rows Number of rows your LCD display has.
 * @param charsize The size in dots that the display has, use LCD_5x10DOTS or LCD_5x8DOTS.
 */
 LiquidCrystal_I2C(uint8_t lcd_addr, uint8_t lcd_cols, uint8_t lcd_rows, uint8_t charsize = LCD_5x8DOTS);

 /**
 * Set the LCD display in the correct begin state, must be called before anything else is done.
 */
 void begin();

 void noBacklight();
 void backlight();
 bool getBacklight();

 inline void blink_on() { blink(); }
 inline void blink_off() { noBlink(); }
 inline void cursor_on() { cursor(); }
 inline void cursor_off() { noCursor(); }

// Compatibility API function aliases
 void setBacklight(uint8_t new_val); // alias for backlight() and nobacklight()
 void load_custom_character(uint8_t char_num, uint8_t *rows); // alias for createChar()
 void printstr(const char[]);

private:
 void send(uint8_t, uint8_t);
 void write4bits(uint8_t);
 void expanderWrite(uint8_t);
 void pulseEnable(uint8_t);
 uint8_t _addr;
 uint8_t _cols;
 uint8_t _rows;
 uint8_t _charsize;
 uint8_t _backlightval;
};

#endif // FDB_LIQUID_CRYSTAL_I2C_H

LiquidCrystal_I2C.cpp

#include "LiquidCrystal_I2C.h"
#include <inttypes.h>
#include <Arduino.h>
#include <Wire.h>

// When the display powers up, it is configured as follows:
//
// 1. Display clear
// 2. Function set:
//    DL = 1; 8-bit interface data
//    N = 0; 1-line display
//    F = 0; 5x8 dot character font
// 3. Display on/off control:
//    D = 0; Display off
//    C = 0; Cursor off
//    B = 0; Blinking off
// 4. Entry mode set:
//    I/D = 1; Increment by 1
//    S = 0; No shift
//
// Note, however, that resetting the Arduino doesn't reset the LCD, so we
// can't assume that its in that state when a sketch starts (and the
// LiquidCrystal constructor is called).

LiquidCrystal_I2C::LiquidCrystal_I2C(uint8_t lcd_addr, uint8_t lcd_cols, uint8_t lcd_rows, uint8_t charsize)
{
 _addr = lcd_addr;
 _cols = lcd_cols;
 _rows = lcd_rows;
 _charsize = charsize;
 _backlightval = LCD_BACKLIGHT;
}

void LiquidCrystal_I2C::begin() {
 Wire.begin();
 setRowOffsets(_cols, _rows);
 _displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_5x8DOTS;

 if (_rows > 1) {
 _displayfunction |= LCD_2LINE;
 }

 // for some 1 line displays you can select a 10 pixel high font
 if ((_charsize != 0) && (_rows == 1)) {
 _displayfunction |= LCD_5x10DOTS;
 }

 // SEE PAGE 45/46 FOR INITIALIZATION SPECIFICATION!
 // according to datasheet, we need at least 40ms after power rises above 2.7V
 // before sending commands. Arduino can turn on way befer 4.5V so we'll wait 50
 delay(50);

 // Now we pull both RS and R/W low to begin commands
 expanderWrite(_backlightval); // reset expanderand turn backlight off (Bit 8 =1)
 delay(1000);

 //put the LCD into 4 bit mode
 // this is according to the hitachi HD44780 datasheet
 // figure 24, pg 46

 // we start in 8bit mode, try to set 4 bit mode
 write4bits(0x03 << 4);
 delayMicroseconds(4500); // wait min 4.1ms

 // second try
 write4bits(0x03 << 4);
 delayMicroseconds(4500); // wait min 4.1ms

 // third go!
 write4bits(0x03 << 4);
 delayMicroseconds(150);

 // finally, set to 4-bit interface
 write4bits(0x02 << 4);

 // set # lines, font size, etc.
 command(LCD_FUNCTIONSET | _displayfunction);

 // turn the display on with no cursor or blinking default
 _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF;
 display();

 // clear it off
 clear();

 // Initialize to default text direction (for roman languages)
 _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT;

 // set the entry mode
 command(LCD_ENTRYMODESET | _displaymode);

 home();
}


// Turn the (optional) backlight off/on
void LiquidCrystal_I2C::noBacklight(void) {
 _backlightval=LCD_NOBACKLIGHT;
 expanderWrite(0);
}

void LiquidCrystal_I2C::backlight(void) {
 _backlightval=LCD_BACKLIGHT;
 expanderWrite(0);
}
bool LiquidCrystal_I2C::getBacklight() {
  return _backlightval == LCD_BACKLIGHT;
}



/************ low level data pushing commands **********/

// write either command or data
void LiquidCrystal_I2C::send(uint8_t value, uint8_t mode) {
 uint8_t highnib=value&0xf0;
 uint8_t lownib=(value<<4)&0xf0;
 write4bits((highnib)|mode);
 write4bits((lownib)|mode);
}

void LiquidCrystal_I2C::write4bits(uint8_t value) {
 expanderWrite(value);
 pulseEnable(value);
}

void LiquidCrystal_I2C::expanderWrite(uint8_t _data){
 Wire.beginTransmission(_addr);
 Wire.write((int)(_data) | _backlightval);
 Wire.endTransmission();
}

void LiquidCrystal_I2C::pulseEnable(uint8_t _data){
 expanderWrite(_data | En); // En high
 delayMicroseconds(1); // enable pulse must be >450ns

 expanderWrite(_data & ~En); // En low
 delayMicroseconds(50); // commands need > 37us to settle
}

void LiquidCrystal_I2C::load_custom_character(uint8_t char_num, uint8_t *rows){
 createChar(char_num, rows);
}

void LiquidCrystal_I2C::setBacklight(uint8_t new_val){
 if (new_val) {
 backlight(); // turn backlight on
 } else {
 noBacklight(); // turn backlight off
 }
}

void LiquidCrystal_I2C::printstr(const char c[]){
 //This function is not identical to the function used for "real" I2C displays
 //it's here so the user sketch doesn't have to be changed
 print(c);
}

Again, it compiles with the HelloWorld example but I’d appreciate if someone could test the examples with an actual setup. I don’t even have one of these so I can’t test anything.

DKWatson:
Is it possible for you to provide a list of the LCD types that you would consider to be included in the class? I'd be willing to set up a test, but the only LCD I have is a generic 16x2.

The ones posted would go with the same library LiquidCrystal that comes stock with the IDE. So whatever LCD you would normally use with that.

So for the code in #2 and #3 the answer to your question is:

From Arduino - LiquidCrystal

This library allows an Arduino board to control LiquidCrystal displays (LCDs) based on the Hitachi HD44780 (or a compatible) chipset, which is found on most text-based LCDs. The library works with in either 4- or 8-bit mode (i.e. using 4 or 8 data lines in addition to the rs, enable, and, optionally, the rw control lines).

The I2C thing is the same. Should work with anything you were going to use LiquidCrystal_I2C with. I didn't change the library functionally, I just moved some common stuff together into a base class.

Right. I have Uno R3 (China) with Mango LCD Keypad Shield currently running with;

//Sample using LiquidCrystal library
#include <LiquidCrystal.h>

/*******************************************************

This program will test the LCD panel and the buttons
Mark Bramwell, July 2010

********************************************************/

// select the pins used on the LCD panel
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

// read the buttons
int read_LCD_buttons()
{
 adc_key_in = analogRead(0);      // read the value from the sensor 
 // my buttons when read are centered at these valies: 0, 144, 329, 504, 741
 // we add approx 50 to those values and check to see if we are close
 if (adc_key_in > 1000) return btnNONE; // We make this the 1st option for speed reasons since it will be the most likely result
 // For V1.1 us this threshold
 if (adc_key_in < 50)   return btnRIGHT;  
 if (adc_key_in < 250)  return btnUP; 
 if (adc_key_in < 450)  return btnDOWN; 
 if (adc_key_in < 650)  return btnLEFT; 
 if (adc_key_in < 850)  return btnSELECT;  

 return btnNONE;  // when all others fail, return this...
}

void setup()
{
 Serial.begin(9600);
 Serial.println("LCD_Test");
 lcd.begin(16, 2);              // start the library
 lcd.setCursor(0,0);
 lcd.print("Push the buttons"); // print a simple message
}
 
void loop()
{
 lcd.setCursor(9,1);            // move cursor to second line "1" and 9 spaces over
 lcd.print(millis()/1000);      // display seconds elapsed since power-up


 lcd.setCursor(0,1);            // move to the begining of the second line
 lcd_key = read_LCD_buttons();  // read the buttons

 switch (lcd_key)               // depending on which button was pushed, we perform an action
 {
   case btnRIGHT:
     {
     lcd.print("RIGHT ");
     break;
     }
   case btnLEFT:
     {
     lcd.print("LEFT   ");
     break;
     }
   case btnUP:
     {
     lcd.print("UP    ");
     break;
     }
   case btnDOWN:
     {
     lcd.print("DOWN  ");
     break;
     }
   case btnSELECT:
     {
     lcd.print("SELECT");
     break;
     }
     case btnNONE:
     {
     lcd.print("NONE  ");
     break;
     }
 }
}

Available now for your tests.

First kick at the cat.

Original library:

Sketch uses 3078 bytes (9%) of program storage space. Maximum is 32256 bytes.
Global variables use 296 bytes (14%) of dynamic memory, leaving 1752 bytes for local variables. Maximum is 2048 bytes.

Your library:

Sketch uses 3100 bytes (9%) of program storage space. Maximum is 32256 bytes.
Global variables use 297 bytes (14%) of dynamic memory, leaving 1751 bytes for local variables.

Screen comes up with 'Push the buttons' but no other display. No timer display and the buttons are not reflected.

Well at least she compiles huh?

I'll have to drag out an LCD and test tomorrow then. I thought it should work right out of the box as a drop-in replacement.

Always a promising start.

Been a while since I looked at this. But the topic came up today. I hooked up an LCD and got it running with the regular stock LiquidCrystal Hello World example. That worked great. Replaced the libraries with the ones I built and I get the same as @DKWatson. It prints the initial "Hello World" great, but then it doesn't count. I added Serial prints to setup and to loop with the loop printing millis /100 every 200ms. The program is continuing to run, but the LCD isn't working right. I notice it looks kind of like the boxes you get when you're sending bad commands real light over the "Hello World".

I've been looking at it for a couple of hours now and I can't see what I'm doing wrong here.

The code as I’m testing: These versions of LiquidCrystal were modified to use a base class.

The odd thing is that I built this base class code out of the code that I cut from the LiquidCystal library. I figured get that working first and then see what it takes to get the others. Now it doesn’t work for some reason.

Who can spot it?

LiquidCrystal.cpp (5.6 KB)

LiquidCrystal.h (1.39 KB)

LCD_BaseClass.cpp (4.04 KB)

LCD_BaseClass.h (1.83 KB)

LCD_HelloWorld.ino (1.79 KB)

No offense, but IMHO, we need another LCD library like we need a hole in our collective heads.

If you comment out the call to setCursor in loop then it will work until it runs out of screen. So it seems to be the call to setCursor, at least in this limited case, that is causing the issue.

DrAzzy:
No offense, but IMHO, we need another LCD library like we need a hole in our collective heads.

I'm not proposing ANY new code here. All I'm doing is trying to cut the existing and well doc'ed LiquidCrystal library into two pieces, one with the high level functions that the others share and one with the low level stuff that they don't.

The goal is that I can write code that uses an LCD where I'm using bit straight data mode like the tutorial and then someone comes along and says they want to use the same code but their LCD is an I2C backpack. I think it would be neat if the same code works for both and all they gotta do is change their library include and their constructor.

If nobody else likes the idea that's cool too. I still want to have it for my own because I do often rebuild things with different parts and it's a common chore to have to refactor code to use a different style of LCD when in reality the two libraries are almost identical in every way.

IDK, maybe it sucks. Right now I just wanna know why it doesn't work.

If you comment out the call to setCursor in loop then it will work until it runs out of screen. So it seems to be the call to setCursor, at least in this limited case, that is causing the issue.

I don't think this is about creating a new LCD library but rather allowing the existing libraries to share the non-hardware specific code. That makes good sense to me.

I think Adafruit did something similar with their Adafruit GFX and Unified sensor libraries.

The question is whether you can get the LCD library authors on board. Some of the popular LiquidCrystal_I2C libraries seem to have been abandoned.

It seems somewhat related to what Arduino is doing with the new Arduino Core API (AKA "Project Chainsaw"), where they are taking all the non-architecture specific code out of the core libraries so that all the hardware packages can share that code:

I've been doing the same thing in my code for the different TFT and OLED displays I've been using. No matter what I'm drawing, it all now works the same. HUGE time & brain saver.

But it was a lot of typing..

-jim lee