Closed Thomascountz closed 1 year ago
In MicroPython, which, to the best of my knowledge, does not support the abc
module for defining abstract base classes, we should be able to achieve a similar effect by defining methods in a base class that raise a NotImplementedError
, signaling that subclasses are expected to provide an implementation for these methods.
class HD44780Controller:
def write(self, payload):
raise NotImplementedError
The motivation behind introducing the
HD44780Controller
interface is to abstract away the specific communication mechanism with the HD44780 LCD controller.The
HD44780
class, which encapsulates the logic of controlling the HD44780 LCD, should ideally not be tightly coupled with a specific I/O expander class such asPCF8574
. Instead, it should work with any class that provides the necessary methods for sending commands and data to the HD44780.In other words, the
HD44780
class needs an object that can "write commands" and "write data" (and eventually read) to the HD44780, but it doesn't need to know the specifics of how this is accomplished. This could be done via the PCF8574, another type of I/O expander, or even directly via GPIO pins on the microcontroller.This is where the
HD44780Controller
interface comes into play. By programming to this interface, theHD44780
class is decoupled from the specific class and can work with any class that implements theHD44780Controller
interface.Create a
Payload
class to represent the data and control signals that need to be sent to the HD44780 controller. This class is immutable and simply holds the values:Define an interface for writing command/data payloads. This could be implemented by any class that controls the HD44780, whether it's an I/O expander like the PCF8574 or a direct connection to the microcontroller:
Move the logic for arranging the byte array into the
PCF8574
class. ThePCF8574
class implements theHD44780Controller
interface, and itswrite
method takes aPayload
object, arranges the bits into the correct positions for the PCF8574's pins, and sends the result to the I2C bus:Change the
HD44780
class to use theHD44780Controller
interface for writing payloads. This way, it doesn't need to know about the specifics of the PCF8574 or any other controller: