026 - ESP32 MicroPython: MFRC522 RFID Module

Introduction

In this article, I will demonstrate how to use an RFID module such as the MFRC522 with ESP32 using MicroPython programming language.

Bill Of Materials

For this lesson, you will need:

  1. An ESP32 development board.
  2. An MFRC522 RFID module kit (RFID reader/write, RFID plastic card, RFID key fobs).
  3. A 16×2 LCD with I2C interface module.
  4. A red LED.
  5. A green LED.
  6. A breadboard.
  7. And some jumper wires.

Circuit Diagram

Hardware Instruction

  1. I connected the RC522 VCC pin or pin # 1 to ESP32 3.3V pin using the red wire.
  2. Its RST pin or pin # 2 to ESP32 GPIO4 pin using the white wire.
  3. Its GND pin or pin # 3 to ESP32 GND pin using the brown wire.
  4. Its IRQ pin or pin # 4 is left unconnected. We will just leaved it not connected and only used a polling method for simplicity.
  5. Its MISO pin or pin # 5 to ESP32 GPIO 19 pin using the blue wire.
  6. Its MOSI pin or pin # 6 to ESP32 GPIO 23 pin using the orange wire.
  7. Its SCK pin or pin # 7 to ESP32 GPIO 18 pin using the yellow wire.
  8. And lastly, its CS pin or pin # 8 to ESP32 GPIO 5 pin using the green wire.
  9. Now for the I2C LCD module, I connected the GND pin to ESP32 GND pin using the brown wire.
  10. Its VCC pin to ESP32 3.3V pin using the red wire.
  11. Its SDA pin to ESP32 GPIO 22 pin using the yellow wire.
  12. Its SCL pin to ESP32 GPIO 21 pin using the orange wire.
  13. I connected the green LED to GPIO 13 and the red LED to GPIO 14.

Video Demonstration

Call To Action

If you have any concern regarding this article, write your message in the comment box.

You might also like to support my journey on Youtube by Subscribing. Click this to Subscribe to TechToTinker Youtube channel.

Thank you and I wish you good health.

Regards, – George Bantique | tech.to.tinker@gmail.com

Source Code

1. Example # 1, exploring the basics:

 1# More details can be found in TechToTinker.blogspot.com 
 2# George Bantique | tech.to.tinker@gmail.com
 3
 4from mfrc522 import MFRC522
 5from machine import Pin
 6from machine import SPI
 7
 8spi = SPI(2, baudrate=2500000, polarity=0, phase=0)
 9# Using Hardware SPI pins:
10#     sck=18   # yellow
11#     mosi=23  # orange
12#     miso=19  # blue
13#     rst=4    # white
14#     cs=5     # green, DS
15# *************************
16# To use SoftSPI,
17# from machine import SOftSPI
18# spi = SoftSPI(baudrate=100000, polarity=0, phase=0, sck=sck, mosi=mosi, miso=miso)
19spi.init()
20rdr = MFRC522(spi=spi, gpioRst=4, gpioCs=5)
21print("Place card")
22
23while True:
24    
25    (stat, tag_type) = rdr.request(rdr.REQIDL)
26    if stat == rdr.OK:
27        (stat, raw_uid) = rdr.anticoll()
28        if stat == rdr.OK:
29            card_id = "uid: 0x%02x%02x%02x%02x" % (raw_uid[0], raw_uid[1], raw_uid[2], raw_uid[3])
30            print(card_id)

2. Example # 2, door security application:

 1# More details can be found in TechToTinker.blogspot.com 
 2# George Bantique | tech.to.tinker@gmail.com
 3
 4from mfrc522 import MFRC522
 5from i2c_lcd import I2cLcd
 6from machine import Pin
 7from machine import SoftI2C
 8from machine import SPI
 9
10DEFAULT_I2C_ADDR = 0x20
11i2c = SoftI2C(scl=Pin(22, Pin.OUT, Pin.PULL_UP),
12              sda=Pin(21, Pin.OUT, Pin.PULL_UP),
13              freq=400000) 
14lcd = I2cLcd(i2c, DEFAULT_I2C_ADDR, 2, 16)
15
16red = Pin(14, Pin.OUT)
17grn = Pin(13, Pin.OUT)
18
19spi = SPI(2, baudrate=2500000, polarity=0, phase=0)
20# Using Hardware SPI pins:
21#     sck=18   # yellow
22#     mosi=23  # orange
23#     miso=19  # blue
24#     rst=4    # white
25#     cs=5     # green, DS
26# *************************
27# To use SoftSPI,
28# from machine import SOftSPI
29# spi = SoftSPI(baudrate=100000, polarity=0, phase=0, sck=sck, mosi=mosi, miso=miso)
30spi.init()
31rdr = MFRC522(spi=spi, gpioRst=4, gpioCs=5)
32
33print("Place card")
34
35lcd.clear()
36lcd.move_to(0, 0)
37lcd.putstr("Scan RFID")
38
39while True:
40    (stat, tag_type) = rdr.request(rdr.REQIDL)
41    if stat == rdr.OK:
42        (stat, raw_uid) = rdr.anticoll()
43        if stat == rdr.OK:
44            lcd.clear()
45            lcd.move_to(0, 0)
46            lcd.putstr("RFID: ")
47            
48            card_id = "0x%02x%02x%02x%02x" %(raw_uid[0], raw_uid[1], raw_uid[2], raw_uid[3])
49            print("UID:", card_id)
50            
51            lcd.move_to(0, 1)
52            if card_id == "0x57c07f5a":
53                grn.value(True)
54                red.value(False)
55                lcd.putstr(" Access Granted ")
56            else:
57                grn.value(False)
58                red.value(True)
59                lcd.putstr(" Access Denied! ")

3. Example # 3, attendance system application:

 1# More details can be found in TechToTinker.blogspot.com 
 2# George Bantique | tech.to.tinker@gmail.com
 3
 4from mfrc522 import MFRC522
 5from i2c_lcd import I2cLcd
 6from machine import Pin
 7from machine import SoftI2C
 8from machine import SPI
 9
10DEFAULT_I2C_ADDR = 0x20
11i2c = SoftI2C(scl=Pin(22, Pin.OUT, Pin.PULL_UP),
12              sda=Pin(21, Pin.OUT, Pin.PULL_UP),
13              freq=400000) 
14lcd = I2cLcd(i2c, DEFAULT_I2C_ADDR, 2, 16)
15
16red = Pin(14, Pin.OUT)
17grn = Pin(13, Pin.OUT)
18
19spi = SPI(2, baudrate=2500000, polarity=0, phase=0)
20# Using Hardware SPI pins:
21#     sck=18   # yellow
22#     mosi=23  # orange
23#     miso=19  # blue
24#     rst=4    # white
25#     cs=5     # green, DS
26# *************************
27# To use SoftSPI,
28# from machine import SOftSPI
29# spi = SoftSPI(baudrate=100000, polarity=0, phase=0, sck=sck, mosi=mosi, miso=miso)
30spi.init()
31rdr = MFRC522(spi=spi, gpioRst=4, gpioCs=5)
32
33rfid_name = ["Teacher1",
34             "Teacher2",
35             "Student1",
36             "Student2",
37             "Student3"]
38rfid_uid = ["0xc97be5a2",
39            "0xe7458e7a",
40            "0x2907b498",
41            "0x29eec498",
42            "0x59e1f097"]
43
44def get_username(uid):
45    index = 0
46    try:
47        index = rfid_uid.index(uid)
48        return rfid_name[index]
49    except:
50        index = -1
51        print("RFID is not recognized")
52        return 0
53
54print("Place card")
55
56lcd.clear()
57lcd.move_to(0, 0)
58lcd.putstr("Scan RFID")
59
60while True:
61    (stat, tag_type) = rdr.request(rdr.REQIDL)
62    if stat == rdr.OK:
63        (stat, raw_uid) = rdr.anticoll()
64        if stat == rdr.OK:
65            lcd.clear()
66            lcd.move_to(0, 0)
67            lcd.putstr("RFID: ")
68            
69            card_id = "0x%02x%02x%02x%02x" %(raw_uid[0], raw_uid[1], raw_uid[2], raw_uid[3])
70            print("UID:", card_id)
71            lcd.putstr(card_id)
72
73            username = get_username(card_id)
74            lcd.move_to(0, 1)
75            if username != 0:
76                grn.value(True)
77                red.value(False)
78                lcd.putstr("Welcome {}".format(username))
79            else:
80                grn.value(False)
81                red.value(True)
82                lcd.putstr(" Access Denied! ")

4. mfrc522.py RFID driver library:

  1# https://github.com/cefn/micropython-mfrc522/blob/master/mfrc522.py
  2
  3from machine import Pin, SPI
  4from os import uname
  5
  6emptyRecv = b""
  7
  8class MFRC522:
  9
 10    GAIN_REG = 0x26
 11    MAX_GAIN = 0x07
 12
 13    OK = 0
 14    NOTAGERR = 1
 15    ERR = 2
 16
 17    REQIDL = 0x26
 18    REQALL = 0x52
 19    AUTHENT1A = 0x60
 20    AUTHENT1B = 0x61
 21
 22    def __init__(self, spi=None, gpioRst=None, gpioCs=None):
 23
 24        if gpioRst is not None:
 25            self.rst = Pin(gpioRst, Pin.OUT)
 26        else:
 27            self.rst = None
 28        assert(gpioCs is not None, "Needs gpioCs") # TODO fails without cableSelect
 29        if gpioCs is not None:
 30            self.cs = Pin(gpioCs, Pin.OUT)
 31        else:
 32            self.cs = None
 33
 34        # TODO CH rationalise which of these are referenced, which can be identical
 35        self.regBuf = bytearray(4)
 36        self.blockWriteBuf = bytearray(18)
 37        self.authBuf = bytearray(12)
 38        self.wregBuf = bytearray(2)
 39        self.rregBuf = bytearray(1)
 40        self.recvBuf = bytearray(16)
 41        self.recvMv = memoryview(self.recvBuf)
 42
 43        if self.rst is not None:
 44            self.rst.value(0)
 45        if self.cs is not None:
 46            self.cs.value(1)
 47
 48        if spi is not None:
 49            self.spi = spi
 50        else:
 51            sck = Pin(14, Pin.OUT)
 52            mosi = Pin(13, Pin.OUT)
 53            miso = Pin(12, Pin.IN)
 54            if uname()[0] == 'WiPy':
 55                self.spi = SPI(0)
 56                self.spi.init(SPI.MASTER, baudrate=1000000, pins=(sck, mosi, miso))
 57            elif uname()[0] == 'esp8266': # TODO update to match https://github.com/cefn/avatap/blob/master/python/host/cockle.py #prepareHost()
 58                self.spi = SPI(baudrate=100000, polarity=0, phase=0, sck=sck, mosi=mosi, miso=miso)
 59                self.spi.init()
 60            else:
 61                raise RuntimeError("Unsupported platform")
 62
 63        if self.rst is not None:
 64            self.rst.value(1)
 65        self.init()
 66
 67    def _wreg(self, reg, val):
 68        if self.cs is not None:
 69            self.cs.value(0)
 70        buf = self.wregBuf
 71        buf[0]=0xff & ((reg << 1) & 0x7e)
 72        buf[1]=0xff & val
 73        self.spi.write(buf)
 74        if self.cs is not None:
 75            self.cs.value(1)
 76
 77    def _rreg(self, reg):
 78        if self.cs is not None:
 79            self.cs.value(0)
 80        buf = self.rregBuf
 81        buf[0]=0xff & (((reg << 1) & 0x7e) | 0x80)
 82        self.spi.write(buf)
 83        val = self.spi.read(1)
 84        if self.cs is not None:
 85            self.cs.value(1)
 86
 87        return val[0]
 88
 89    def _sflags(self, reg, mask):
 90        self._wreg(reg, self._rreg(reg) | mask)
 91
 92    def _cflags(self, reg, mask):
 93        self._wreg(reg, self._rreg(reg) & (~mask))
 94
 95    def _tocard(self, cmd, send, into=None):
 96
 97        recv = emptyRecv
 98        bits = irq_en = wait_irq = n = 0
 99        stat = self.ERR
100
101        if cmd == 0x0E:
102            irq_en = 0x12
103            wait_irq = 0x10
104        elif cmd == 0x0C:
105            irq_en = 0x77
106            wait_irq = 0x30
107
108        self._wreg(0x02, irq_en | 0x80)
109        self._cflags(0x04, 0x80)
110        self._sflags(0x0A, 0x80)
111        self._wreg(0x01, 0x00)
112
113        for c in send:
114            self._wreg(0x09, c)
115        self._wreg(0x01, cmd)
116
117        if cmd == 0x0C:
118            self._sflags(0x0D, 0x80)
119
120        i = 2000
121        while True:
122            n = self._rreg(0x04)
123            i -= 1
124            if ~((i != 0) and ~(n & 0x01) and ~(n & wait_irq)):
125                break
126
127        self._cflags(0x0D, 0x80)
128
129        if i:
130            if (self._rreg(0x06) & 0x1B) == 0x00:
131                stat = self.OK
132
133                if n & irq_en & 0x01:
134                    stat = self.NOTAGERR
135                elif cmd == 0x0C:
136                    n = self._rreg(0x0A)
137                    lbits = self._rreg(0x0C) & 0x07
138                    if lbits != 0:
139                        bits = (n - 1) * 8 + lbits
140                    else:
141                        bits = n * 8
142
143                    if n == 0:
144                        n = 1
145                    elif n > 16:
146                        n = 16
147
148                    if into is None:
149                        recv = self.recvBuf
150                    else:
151                        recv = into
152                    pos = 0
153                    while pos < n:
154                        recv[pos] = self._rreg(0x09)
155                        pos += 1
156                    if into is None:
157                        recv = self.recvMv[:n]
158                    else:
159                        recv = into
160
161            else:
162                stat = self.ERR
163
164        return stat, recv, bits
165
166    def _assign_crc(self, data, count):
167
168        self._cflags(0x05, 0x04)
169        self._sflags(0x0A, 0x80)
170
171        dataPos = 0
172        while dataPos < count:
173            self._wreg(0x09, data[dataPos])
174            dataPos += 1
175
176        self._wreg(0x01, 0x03)
177
178        i = 0xFF
179        while True:
180            n = self._rreg(0x05)
181            i -= 1
182            if not ((i != 0) and not (n & 0x04)):
183                break
184
185        data[count] = self._rreg(0x22)
186        data[count + 1] = self._rreg(0x21)
187
188    def init(self):
189
190        self.reset()
191        self._wreg(0x2A, 0x8D)
192        self._wreg(0x2B, 0x3E)
193        self._wreg(0x2D, 30)
194        self._wreg(0x2C, 0)
195        self._wreg(0x15, 0x40)
196        self._wreg(0x11, 0x3D)
197        self.set_gain(self.MAX_GAIN)
198        self.antenna_on()
199
200
201    def reset(self):
202        self._wreg(0x01, 0x0F)
203
204    def antenna_on(self, on=True):
205
206        if on and ~(self._rreg(0x14) & 0x03):
207            self._sflags(0x14, 0x03)
208        else:
209            self._cflags(0x14, 0x03)
210
211    def request(self, mode):
212
213        self._wreg(0x0D, 0x07)
214        (stat, recv, bits) = self._tocard(0x0C, [mode])
215
216        if (stat != self.OK) | (bits != 0x10):
217            stat = self.ERR
218
219        return stat, bits
220
221    def anticoll(self):
222
223        ser_chk = 0
224        ser = [0x93, 0x20]
225
226        self._wreg(0x0D, 0x00)
227        (stat, recv, bits) = self._tocard(0x0C, ser)
228
229        if stat == self.OK:
230            if len(recv) == 5:
231                for i in range(4):
232                    ser_chk = ser_chk ^ recv[i]
233                if ser_chk != recv[4]:
234                    stat = self.ERR
235            else:
236                stat = self.ERR
237
238        # CH Note bytearray allocation here
239        return stat, bytearray(recv)
240
241    def select_tag(self, ser):
242        # TODO CH normalise all list manipulation to bytearray, avoid below allocation
243        buf = bytearray(9)
244        buf[0] = 0x93
245        buf[1] = 0x70
246        buf[2:7] = ser
247        self._assign_crc(buf, 7)
248        (stat, recv, bits) = self._tocard(0x0C, buf)
249        return self.OK if (stat == self.OK) and (bits == 0x18) else self.ERR
250
251    def auth(self, mode, addr, sect, ser):
252        # TODO CH void ser[:4] implicit list allocation
253        buf = self.authBuf
254        buf[0]=mode # A or B
255        buf[1]=addr # block
256        buf[2:8]=sect # key bytes
257        buf[8:12]=ser[:4] # 4 bytes of id
258        return self._tocard(0x0E, buf)[0]
259
260    # TODO this may well need to be implemented for vault to properly back out from a card session
261    # TODO how, why, when is 'HaltA' needed? see https://github.com/cefn/micropython-mfrc522/issues/1
262    def halt_a(self):
263        pass
264
265    def stop_crypto1(self):
266        self._cflags(0x08, 0x08)
267
268    def set_gain(self, gain):
269        assert gain <= self.MAX_GAIN
270        # clear bits
271        self._cflags(self.GAIN_REG, 0x07<< 4)
272        # set bits according to gain
273        self._sflags(self.GAIN_REG, gain << 4)
274
275    def read(self, addr, into = None):
276        buf = self.regBuf
277        buf[0]=0x30
278        buf[1]=addr
279        self._assign_crc(buf, 2)
280        (stat, recv, _) = self._tocard(0x0C, buf, into=into)
281        # TODO this logic probably wrong (should be 'into is None'?)
282        if into is None: # superstitiously avoid returning read buffer memoryview
283            # CH Note bytearray allocation here
284            recv = bytearray(recv)
285        return recv if stat == self.OK else None
286
287    def write(self, addr, data):
288        buf = self.regBuf
289        buf[0] = 0xA0
290        buf[1] = addr
291        self._assign_crc(buf, 2)
292        (stat, recv, bits) = self._tocard(0x0C, buf)
293
294        if not (stat == self.OK) or not (bits == 4) or not ((recv[0] & 0x0F) == 0x0A):
295            stat = self.ERR
296        else:
297            buf = self.blockWriteBuf
298
299            i = 0
300            while i < 16:
301                buf[i] = data[i]  # TODO CH eliminate this, accelerate it?
302                i += 1
303
304            self._assign_crc(buf, 16)
305            (stat, recv, bits) = self._tocard(0x0C, buf)
306            if not (stat == self.OK) or not (bits == 4) or not ((recv[0] & 0x0F) == 0x0A):
307                stat = self.ERR
308
309        return stat

5. lcd_api.py LCD driver base library:

  1"""Provides an API for talking to HD44780 compatible character LCDs.""" 
  2import time 
  3class LcdApi: 
  4    """Implements the API for talking with HD44780 compatible character LCDs. 
  5    This class only knows what commands to send to the LCD, and not how to get 
  6    them to the LCD. 
  7    It is expected that a derived class will implement the hal_xxx functions. 
  8    """ 
  9    # The following constant names were lifted from the avrlib lcd.h 
 10    # header file, however, I changed the definitions from bit numbers 
 11    # to bit masks. 
 12    # 
 13    # HD44780 LCD controller command set 
 14    LCD_CLR = 0x01              # DB0: clear display 
 15    LCD_HOME = 0x02             # DB1: return to home position 
 16    LCD_ENTRY_MODE = 0x04       # DB2: set entry mode 
 17    LCD_ENTRY_INC = 0x02        # --DB1: increment 
 18    LCD_ENTRY_SHIFT = 0x01      # --DB0: shift 
 19    LCD_ON_CTRL = 0x08          # DB3: turn lcd/cursor on 
 20    LCD_ON_DISPLAY = 0x04       # --DB2: turn display on 
 21    LCD_ON_CURSOR = 0x02        # --DB1: turn cursor on 
 22    LCD_ON_BLINK = 0x01         # --DB0: blinking cursor 
 23    LCD_MOVE = 0x10             # DB4: move cursor/display 
 24    LCD_MOVE_DISP = 0x08        # --DB3: move display (0-> move cursor) 
 25    LCD_MOVE_RIGHT = 0x04       # --DB2: move right (0-> left) 
 26    LCD_FUNCTION = 0x20         # DB5: function set 
 27    LCD_FUNCTION_8BIT = 0x10    # --DB4: set 8BIT mode (0->4BIT mode) 
 28    LCD_FUNCTION_2LINES = 0x08  # --DB3: two lines (0->one line) 
 29    LCD_FUNCTION_10DOTS = 0x04  # --DB2: 5x10 font (0->5x7 font) 
 30    LCD_FUNCTION_RESET = 0x30   # See "Initializing by Instruction" section 
 31    LCD_CGRAM = 0x40            # DB6: set CG RAM address 
 32    LCD_DDRAM = 0x80            # DB7: set DD RAM address 
 33    LCD_RS_CMD = 0 
 34    LCD_RS_DATA = 1 
 35    LCD_RW_WRITE = 0 
 36    LCD_RW_READ = 1 
 37    def __init__(self, num_lines, num_columns): 
 38        self.num_lines = num_lines 
 39        if self.num_lines > 4: 
 40            self.num_lines = 4 
 41        self.num_columns = num_columns 
 42        if self.num_columns > 40: 
 43            self.num_columns = 40 
 44        self.cursor_x = 0 
 45        self.cursor_y = 0 
 46        self.implied_newline = False 
 47        self.backlight = True 
 48        self.display_off() 
 49        self.backlight_on() 
 50        self.clear() 
 51        self.hal_write_command(self.LCD_ENTRY_MODE | self.LCD_ENTRY_INC) 
 52        self.hide_cursor() 
 53        self.display_on() 
 54    def clear(self): 
 55        """Clears the LCD display and moves the cursor to the top left 
 56        corner. 
 57        """ 
 58        self.hal_write_command(self.LCD_CLR) 
 59        self.hal_write_command(self.LCD_HOME) 
 60        self.cursor_x = 0 
 61        self.cursor_y = 0 
 62    def show_cursor(self): 
 63        """Causes the cursor to be made visible.""" 
 64        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY | 
 65                               self.LCD_ON_CURSOR) 
 66    def hide_cursor(self): 
 67        """Causes the cursor to be hidden.""" 
 68        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY) 
 69    def blink_cursor_on(self): 
 70        """Turns on the cursor, and makes it blink.""" 
 71        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY | 
 72                               self.LCD_ON_CURSOR | self.LCD_ON_BLINK) 
 73    def blink_cursor_off(self): 
 74        """Turns on the cursor, and makes it no blink (i.e. be solid).""" 
 75        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY | 
 76                               self.LCD_ON_CURSOR) 
 77    def display_on(self): 
 78        """Turns on (i.e. unblanks) the LCD.""" 
 79        self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY) 
 80    def display_off(self): 
 81        """Turns off (i.e. blanks) the LCD.""" 
 82        self.hal_write_command(self.LCD_ON_CTRL) 
 83    def backlight_on(self): 
 84        """Turns the backlight on. 
 85        This isn't really an LCD command, but some modules have backlight 
 86        controls, so this allows the hal to pass through the command. 
 87        """ 
 88        self.backlight = True 
 89        self.hal_backlight_on() 
 90    def backlight_off(self): 
 91        """Turns the backlight off. 
 92        This isn't really an LCD command, but some modules have backlight 
 93        controls, so this allows the hal to pass through the command. 
 94        """ 
 95        self.backlight = False 
 96        self.hal_backlight_off() 
 97    def move_to(self, cursor_x, cursor_y): 
 98        """Moves the cursor position to the indicated position. The cursor 
 99        position is zero based (i.e. cursor_x == 0 indicates first column). 
100        """ 
101        self.cursor_x = cursor_x 
102        self.cursor_y = cursor_y 
103        addr = cursor_x & 0x3f 
104        if cursor_y & 1: 
105            addr += 0x40    # Lines 1 & 3 add 0x40 
106        if cursor_y & 2:    # Lines 2 & 3 add number of columns 
107            addr += self.num_columns 
108        self.hal_write_command(self.LCD_DDRAM | addr) 
109    def putchar(self, char): 
110        """Writes the indicated character to the LCD at the current cursor 
111        position, and advances the cursor by one position. 
112        """ 
113        if char == 'n': 
114            if self.implied_newline: 
115                # self.implied_newline means we advanced due to a wraparound, 
116                # so if we get a newline right after that we ignore it. 
117                pass 
118            else: 
119                self.cursor_x = self.num_columns 
120        else: 
121            self.hal_write_data(ord(char)) 
122            self.cursor_x += 1 
123        if self.cursor_x >= self.num_columns: 
124            self.cursor_x = 0 
125            self.cursor_y += 1 
126            self.implied_newline = (char != 'n') 
127        if self.cursor_y >= self.num_lines: 
128            self.cursor_y = 0 
129        self.move_to(self.cursor_x, self.cursor_y) 
130    def putstr(self, string): 
131        """Write the indicated string to the LCD at the current cursor 
132        position and advances the cursor position appropriately. 
133        """ 
134        for char in string: 
135            self.putchar(char) 
136    def custom_char(self, location, charmap): 
137        """Write a character to one of the 8 CGRAM locations, available 
138        as chr(0) through chr(7). 
139        """ 
140        location &= 0x7 
141        self.hal_write_command(self.LCD_CGRAM | (location << 3)) 
142        self.hal_sleep_us(40) 
143        for i in range(8): 
144            self.hal_write_data(charmap[i]) 
145            self.hal_sleep_us(40) 
146        self.move_to(self.cursor_x, self.cursor_y)
147        
148    def hal_backlight_on(self): 
149        """Allows the hal layer to turn the backlight on. 
150        If desired, a derived HAL class will implement this function. 
151        """ 
152        pass 
153    def hal_backlight_off(self): 
154        """Allows the hal layer to turn the backlight off. 
155        If desired, a derived HAL class will implement this function. 
156        """ 
157        pass 
158    def hal_write_command(self, cmd): 
159        """Write a command to the LCD. 
160        It is expected that a derived HAL class will implement this 
161        function. 
162        """ 
163        raise NotImplementedError 
164    def hal_write_data(self, data): 
165        """Write data to the LCD. 
166        It is expected that a derived HAL class will implement this 
167        function. 
168        """ 
169        raise NotImplementedError 
170    def hal_sleep_us(self, usecs): 
171        """Sleep for some time (given in microseconds).""" 
172        time.sleep_us(usecs)

6. i2c_lcd.py LCD driver library for I2C:

 1"""Implements a HD44780 character LCD connected via PCF8574 on I2C. 
 2   This was tested with: https://www.wemos.cc/product/d1-mini.html""" 
 3from lcd_api import LcdApi 
 4from machine import I2C 
 5from time import sleep_ms 
 6# The PCF8574 has a jumper selectable address: 0x20 - 0x27 
 7#DEFAULT_I2C_ADDR = 0x20 
 8# Defines shifts or masks for the various LCD line attached to the PCF8574 
 9MASK_RS = 0x01 
10MASK_RW = 0x02 
11MASK_E = 0x04 
12SHIFT_BACKLIGHT = 3 
13SHIFT_DATA = 4 
14class I2cLcd(LcdApi): 
15    """Implements a HD44780 character LCD connected via PCF8574 on I2C.""" 
16    def __init__(self, i2c, i2c_addr, num_lines, num_columns): 
17        self.i2c = i2c 
18        self.i2c_addr = i2c_addr 
19        self.i2c.writeto(self.i2c_addr, bytearray([0])) 
20        sleep_ms(20)   # Allow LCD time to powerup 
21        # Send reset 3 times 
22        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET) 
23        sleep_ms(5)    # need to delay at least 4.1 msec 
24        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET) 
25        sleep_ms(1) 
26        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET) 
27        sleep_ms(1) 
28        # Put LCD into 4 bit mode 
29        self.hal_write_init_nibble(self.LCD_FUNCTION) 
30        sleep_ms(1) 
31        LcdApi.__init__(self, num_lines, num_columns) 
32        cmd = self.LCD_FUNCTION 
33        if num_lines > 1: 
34            cmd |= self.LCD_FUNCTION_2LINES 
35        self.hal_write_command(cmd) 
36    def hal_write_init_nibble(self, nibble): 
37        """Writes an initialization nibble to the LCD. 
38        This particular function is only used during initialization. 
39        """ 
40        byte = ((nibble >> 4) & 0x0f) << SHIFT_DATA 
41        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
42        self.i2c.writeto(self.i2c_addr, bytearray([byte])) 
43    def hal_backlight_on(self): 
44        """Allows the hal layer to turn the backlight on.""" 
45        self.i2c.writeto(self.i2c_addr, bytearray([1 << SHIFT_BACKLIGHT])) 
46    def hal_backlight_off(self): 
47        """Allows the hal layer to turn the backlight off.""" 
48        self.i2c.writeto(self.i2c_addr, bytearray([0])) 
49    def hal_write_command(self, cmd): 
50        """Writes a command to the LCD. 
51        Data is latched on the falling edge of E. 
52        """ 
53        byte = ((self.backlight << SHIFT_BACKLIGHT) | (((cmd >> 4) & 0x0f) << SHIFT_DATA)) 
54        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
55        self.i2c.writeto(self.i2c_addr, bytearray([byte])) 
56        byte = ((self.backlight << SHIFT_BACKLIGHT) | ((cmd & 0x0f) << SHIFT_DATA)) 
57        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
58        self.i2c.writeto(self.i2c_addr, bytearray([byte])) 
59        if cmd <= 3: 
60            # The home and clear commands require a worst case delay of 4.1 msec 
61            sleep_ms(5) 
62    def hal_write_data(self, data): 
63        """Write data to the LCD.""" 
64        byte = (MASK_RS | (self.backlight << SHIFT_BACKLIGHT) | (((data >> 4) & 0x0f) << SHIFT_DATA)) 
65        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
66        self.i2c.writeto(self.i2c_addr, bytearray([byte])) 
67        byte = (MASK_RS | (self.backlight << SHIFT_BACKLIGHT) | ((data & 0x0f) << SHIFT_DATA)) 
68        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
69        self.i2c.writeto(self.i2c_addr, bytearray([byte]))

References And Credits

  1. Cefn Hoile Github for MFRC522: https://github.com/cefn/micropython-mfrc522

  2. Dave Hylands Github for I2C LCD: https://github.com/dhylands/python_lcd



Posts in this series



No comments yet!

GitHub-flavored Markdown & a sane subset of HTML is supported.