049 - MicroPython TechNotes: MP3 Player

Introduction

In this article, I will discuss on how to use an MP3 Player module interfaced to ESP32 with MicroPython programming language.

What I have is an MP3 Player module from Gorillacell ESP32 development kit. It uses the YX5300 MP3 audio chip which is capable of playing common audio files such as mp3 and wav files. The MP3 Player module kit includes: 1 piece of 8 Ohms speaker and of course the mp3 player board itself. The mp3 player board has microSD card slot and an audio output connector or it can also be output to 3.5mm audio jack.

Pinout

The mp3 player has 4 pins which are:

  1. GND – for the ground pins.
  2. VCC – for the supply voltage.
  3. Tx – for the UART serial transmit pin.
  4. Rx – for the UART serial receive pin.

Bill Of Materials

In order to follow this, you will need the following:

  1. An ESP32 development board.
  2. A Gorillacell ESP32 shield (optional, you may use breadboard or directly connect it to ESP32 pins).
  3. A 4-pin Dupont jumper wires.
  4. And of course, the Gorillacell MP3 Player module.
  5. For example # 2, you will need additional Analog Touch Sensor module, 16×2 LCD module, and its corresponding jumper wires.

Hardware Instruction

  1. First, attach the ESP32 on top of the ESP32 shield and make sure that both USB port are on the same side.
  2. Next, attach the dupont wires to the MP3 Player module by following a color coding such that black is for the ground, red is for the VCC, yellow is for the Tx pin, and white is for the Rx pin.
  3. Next, attach the other end of the dupont wires to the ESP32 shield by matching the colors of the wires to the colors of the pin headers such as black is to black, red is to red, yellow and the following colors to the yellow pin headers. For this lesson, Tx pin is connected to GPIO 25 and Rx pin is connected to GPIO 26.
  4. Next, power the ESP32 shield using external power supply with a type-C USB cable and make sure that the power switch is set to ON state.
  5. Lastly, connect the ESP32 to the computer through a micro USB cable.
  6. For the example # 2, attach the Analog Touch Sensor module on GPIO 32 and the 16×2 LCD module on GPIO 21 (SDA) and GPIO 22 (SCL).

Software Instruction

  1. Copy the provided example source code in the SOURCE CODE section and for the example # 2, you will also need to upload the i2c_lcd.py library to your ESP32 MicroPython root directory by clicking the File menu, select Save As, select MicroPython Device, name it as i2c_lcd.py, and hit OK.

Video Demonstration

Call To Action

If you have any concern regarding this lesson, be sure to write your message in the comment section.

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

May you have a blessed day.

Thank you, George Bantique | tech.to.tinker@gmail.com

Source Code

1. Example # 1, exploring the mp3 player module through the REPL:

 1# More details can be found in TechToTinker.blogspot.com 
 2# George Bantique | tech.to.tinker@gmail.com
 3
 4from machine import UART
 5from machine import Pin
 6
 7STA_BYTE = 0x7E
 8VER_BYTE = 0xFF
 9LEN_BYTE = 0x06
10FDB_BYTE = 0x00
11END_BYTE = 0xEF
12
13class GORILLA_MP3PLAYER():
14#     player_volume = 20
15#     is_mute = False
16    
17    def __init__(self,tx,rx):
18        self.uart = UART(2, baudrate=9600, tx=tx, rx=rx)
19        self.player_volume = 20
20        self.is_mute = True
21        self.setVolume(self.player_volume)
22        
23    def command(self, cmd, hbyte_data, lbyte_data):
24        self.uart.write(bytes([STA_BYTE]))
25        self.uart.write(bytes([VER_BYTE]))
26        self.uart.write(bytes([LEN_BYTE]))
27        self.uart.write(bytes([cmd]))
28        self.uart.write(bytes([FDB_BYTE]))
29        self.uart.write(bytes([hbyte_data]))
30        self.uart.write(bytes([lbyte_data]))
31        self.uart.write(bytes([END_BYTE]))
32
33    def playNext(self):
34        self.command(0x01, 0, 0)
35        
36    def playPrevious(self):
37        self.command(0x02, 0, 0)
38        
39    def playIndex(self,index):
40        self.command(0x03, 0, index)
41        
42    def volumeUp(self):
43        if self.player_volume < 30:
44            self.player_volume += 1
45            self.command(0x04, 0, 0)
46            print("Current volume: {}".format(self.player_volume))
47        else:
48            print("Max volume set\r\n")
49            
50    def volumeDown(self):
51        if self.player_volume != 0:
52            self.player_volume -= 1
53            self.command(0x05, 0, 0)
54            print("Current volume: {}".format(self.player_volume))
55        else:
56            print("Volume set to MUTE\r\n")
57            
58    def setVolume(self, volume):
59        self.player_volume = volume
60        self.command(0x06, 0, volume)
61        
62    def sleep(self):
63        self.command(0x0A, 0, 0)
64        
65    def wakeUp(self):
66        self.command(0x0B, 0, 0)
67        
68    def reset(self):
69        self.command(0x0C, 0, 0)
70        
71    def play(self):
72        self.command(0x0D, 0, 1)
73        self.is_mute = False
74        
75    def pause(self):
76        self.command(0x0E, 0, 0)
77        
78    def playFolder(self, folder, file):
79        self.command(0x0F, folder, file)
80        
81    def playStop(self):
82        self.command(0x16, 0, 0)
83        
84    def playMute(self):
85        curr_vol = self.player_volume
86        if self.is_mute:
87            self.setVolume(curr_vol)
88            self.is_mute = False
89        else:
90            self.setVolume(0)
91            self.is_mute = True
92        self.player_volume = curr_vol
93
94mp3 = GORILLA_MP3PLAYER(rx=25,tx=26)

2. Example # 2, sample application of the mp3 player module, analog touch sensor, and the 16×2 LCD module:

  1# More details can be found in TechToTinker.blogspot.com 
  2# George Bantique | tech.to.tinker@gmail.com
  3
  4from machine import Pin
  5from machine import UART
  6from machine import ADC
  7from machine import SoftI2C
  8from i2c_lcd import I2cLcd
  9from time import sleep_ms
 10
 11STA_BYTE = 0x7E
 12VER_BYTE = 0xFF
 13LEN_BYTE = 0x06
 14FDB_BYTE = 0x00
 15END_BYTE = 0xEF
 16
 17class GORILLA_MP3PLAYER():
 18#     player_volume = 20
 19#     is_mute = False
 20    
 21    def __init__(self,tx,rx):
 22        self.uart = UART(2, baudrate=9600, tx=tx, rx=rx)
 23        self.player_volume = 20
 24        self.is_mute = True
 25        self.setVolume(self.player_volume)
 26        
 27    def command(self, cmd, hbyte_data, lbyte_data):
 28        self.uart.write(bytes([STA_BYTE]))
 29        self.uart.write(bytes([VER_BYTE]))
 30        self.uart.write(bytes([LEN_BYTE]))
 31        self.uart.write(bytes([cmd]))
 32        self.uart.write(bytes([FDB_BYTE]))
 33        self.uart.write(bytes([hbyte_data]))
 34        self.uart.write(bytes([lbyte_data]))
 35        self.uart.write(bytes([END_BYTE]))
 36
 37    def playNext(self):
 38        self.command(0x01, 0, 0)
 39        
 40    def playPrevious(self):
 41        self.command(0x02, 0, 0)
 42        
 43    def playIndex(self,index):
 44        self.command(0x03, 0, index)
 45        
 46    def volumeUp(self):
 47        if self.player_volume < 30:
 48            self.player_volume += 1
 49            self.command(0x04, 0, 0)
 50            print("Current volume: {}".format(self.player_volume))
 51        else:
 52            print("Max volume set\r\n")
 53            
 54    def volumeDown(self):
 55        if self.player_volume != 0:
 56            self.player_volume -= 1
 57            self.command(0x05, 0, 0)
 58            print("Current volume: {}".format(self.player_volume))
 59        else:
 60            print("Volume set to MUTE\r\n")
 61            
 62    def setVolume(self, volume):
 63        self.player_volume = volume
 64        self.command(0x06, 0, volume)
 65        
 66    def sleep(self):
 67        self.command(0x0A, 0, 0)
 68        
 69    def wakeUp(self):
 70        self.command(0x0B, 0, 0)
 71        
 72    def reset(self):
 73        self.command(0x0C, 0, 0)
 74        
 75    def play(self):
 76        self.command(0x0D, 0, 1)
 77        self.is_mute = False
 78        
 79    def pause(self):
 80        self.command(0x0E, 0, 0)
 81        
 82    def playFolder(self, folder, file):
 83        self.command(0x0F, folder, file)
 84        
 85    def playStop(self):
 86        self.command(0x16, 0, 0)
 87        
 88    def playMute(self):
 89        curr_vol = self.player_volume
 90        if self.is_mute:
 91            self.setVolume(curr_vol)
 92            self.is_mute = False
 93        else:
 94            self.setVolume(0)
 95            self.is_mute = True
 96        self.player_volume = curr_vol
 97        
 98class GORILLA_ANALOGTOUCHSENSOR():
 99    def __init__(self, pin):
100        self.pin = Pin(pin, Pin.IN)
101        self.ats = ADC(self.pin)
102        self.ats.atten(ADC.ATTN_11DB)
103        
104    def get_raw(self):
105        return self.ats.read()
106    
107    def get_key(self):
108        adc_value = self.ats.read()
109        if (adc_value > 640) and (adc_value < 700):     # 1
110            key = '1'
111        elif (adc_value > 1470) and (adc_value < 1530): # 2
112            key = '2'
113        elif (adc_value > 2310) and (adc_value < 2370): # 3
114            key = '3'
115        elif (adc_value > 3170) and (adc_value < 3230): # 4
116            key = '4'
117        else:
118            key = '0'
119        return key
120
121mp3 = GORILLA_MP3PLAYER(rx=25,tx=26)
122ats = GORILLA_ANALOGTOUCHSENSOR(32)
123i2c = SoftI2C(scl=Pin(22, Pin.OUT, Pin.PULL_UP), sda=Pin(21, Pin.OUT, Pin.PULL_UP))
124lcd = I2cLcd(i2c, 0x20, 2, 16)
125
126#     **************************
127#       MP3 Player Menu System
128#     **************************
129#     Playback
130#         Play/Pause
131#         Play Prev
132#         Play Next
133#         Play Stop
134#     Volume
135#         Mute Sound
136#         Volume Up
137#         Volume Down
138#         Set Volume
139#     Advance
140#         Play Index
141#         Play Folder
142#     System
143#         Sleep
144#         Wakeup
145#         About
146menu = [['Playback', 'Play/Pause', 'Play Prev', 'Play Next', 'Play Stop'],
147        ['Volume', 'Mute Sound', 'Volume Up', 'Volume Down', 'Reset Volume']]
148mainmenu_idx = 0
149submenu_idx = 1
150in_submenu = False
151is_playing = False
152
153def execute_menu():
154    global mainmenu_idx
155    global submenu_idx
156    global is_playing
157    
158    if mainmenu_idx==0:      # PLAYBACK
159        if submenu_idx==1:   # Play / Pause
160            if is_playing:   # Currently playing, so do pause
161                mp3.pause()
162                is_playing = False
163            else:            # Current pause/stop, so do play
164                mp3.play()
165                is_playing = True
166        elif submenu_idx==2: # Play previous
167            mp3.playPrevious()
168        elif submenu_idx==3: # Play next
169            mp3.playNext()
170        elif submenu_idx==4: # Play stop
171            mp3.playStop()
172            is_playing = False
173    elif mainmenu_idx==1:    # VOLUME
174        if submenu_idx==1:   # Mute
175            mp3.playMute()
176        elif submenu_idx==2: # Volume Up
177            mp3.volumeUp()
178        elif submenu_idx==3: # Volume Down
179            mp3.volumeDown()
180        elif submenu_idx==4: # Set volume
181            mp3.setVolume(20)
182    else:
183        pass
184
185def process_menu(key):
186    global mainmenu_idx
187    global submenu_idx
188    global in_submenu
189
190    if key == '1':   # Use as BACK key
191        in_submenu = False
192        submenu_idx = 1
193    elif key == '2': # Use as LEFT key
194        if in_submenu:
195            if submenu_idx > 0:
196                submenu_idx -= 1
197        else:
198            if mainmenu_idx > 0:
199                mainmenu_idx -= 1
200    elif key == '3': # Use as RIGHT key
201        if in_submenu:
202            if submenu_idx < len(menu[mainmenu_idx])-1:
203                submenu_idx += 1
204        else:
205            if mainmenu_idx < len(menu)-1:
206                mainmenu_idx += 1
207    elif key == '4':   # Use as ENTER key
208        if in_submenu:
209            execute_menu() # Executes are all in sub menus
210        else: # in mainmenu
211            in_submenu = True
212            submenu_idx = 0
213        
214    else:              # None is press
215        pass
216    
217    if key != '0': # Update only when a key is pressed!
218        update_display()
219        
220
221def update_display():
222    global submenu_idx
223    
224    lcd.clear()
225
226    if in_submenu:
227        if submenu_idx==0:                                # index 0
228            lcd.setcursor(1,0)
229            lcd.putstr(menu[mainmenu_idx][submenu_idx])
230            lcd.setcursor(2,1)
231            lcd.putstr(menu[mainmenu_idx][submenu_idx+1])
232            lcd.setcursor(1,1)
233            submenu_idx = 1
234        elif submenu_idx==1:                              # index 1
235            lcd.setcursor(1,0)
236            lcd.putstr(menu[mainmenu_idx][submenu_idx-1])
237            lcd.setcursor(2,1)
238            lcd.putstr(menu[mainmenu_idx][submenu_idx])
239            lcd.setcursor(1,1)
240        elif (submenu_idx==len(menu[mainmenu_idx])-1):    # last index
241            lcd.setcursor(2,0)
242            lcd.putstr(menu[mainmenu_idx][submenu_idx-1])
243            lcd.setcursor(2,1)
244            lcd.putstr(menu[mainmenu_idx][submenu_idx])
245            lcd.setcursor(1,1)
246        else:                                             # middle index
247            lcd.setcursor(2,0)
248            lcd.putstr(menu[mainmenu_idx][submenu_idx])
249            lcd.setcursor(2,1)
250            lcd.putstr(menu[mainmenu_idx][submenu_idx+1])
251            lcd.setcursor(1,0)
252        lcd.putstr('>')
253    else: # means in main menu
254        if (mainmenu_idx==len(menu)-1):        # mainmenu index @ end of the array
255          lcd.setcursor(1,0)
256          lcd.putstr(menu[mainmenu_idx-1][0])
257          lcd.setcursor(1,1)
258          lcd.putstr(menu[mainmenu_idx][0])
259          lcd.setcursor(0,1)
260        else:
261          lcd.setcursor(1,0)
262          lcd.putstr(menu[mainmenu_idx][0])
263          lcd.setcursor(1,1)
264          lcd.putstr(menu[mainmenu_idx+1][0])
265          lcd.setcursor(0,0)
266        lcd.putstr(">")
267
268
269update_display()
270
271while True:
272    process_menu( ats.get_key() )
273    sleep_ms(150)

3. i2c_lcd.py:

  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 setcursor(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 &s; 0x3f 
104        if cursor_y &s; 1: 
105            addr += 0x40    # Lines 1 &s; 3 add 0x40 
106        if cursor_y &s; 2:    # Lines 2 &s; 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.setcursor(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 &s;= 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.setcursor(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)
173
174
175
176"""Implements a HD44780 character LCD connected via PCF8574 on I2C. 
177   This was tested with: https://www.wemos.cc/product/d1-mini.html""" 
178# from lcd_api import LcdApi 
179from machine import I2C 
180from time import sleep_ms 
181# The PCF8574 has a jumper selectable address: 0x20 - 0x27 
182#DEFAULT_I2C_ADDR = 0x20 
183# Defines shifts or masks for the various LCD line attached to the PCF8574 
184MASK_RS = 0x01 
185MASK_RW = 0x02 
186MASK_E = 0x04 
187SHIFT_BACKLIGHT = 3 
188SHIFT_DATA = 4 
189class I2cLcd(LcdApi): 
190    """Implements a HD44780 character LCD connected via PCF8574 on I2C.""" 
191    def __init__(self, i2c, i2c_addr, num_lines, num_columns): 
192        self.i2c = i2c 
193        self.i2c_addr = i2c_addr 
194        self.i2c.writeto(self.i2c_addr, bytearray([0])) 
195        sleep_ms(20)   # Allow LCD time to powerup 
196        # Send reset 3 times 
197        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET) 
198        sleep_ms(5)    # need to delay at least 4.1 msec 
199        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET) 
200        sleep_ms(1) 
201        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET) 
202        sleep_ms(1) 
203        # Put LCD into 4 bit mode 
204        self.hal_write_init_nibble(self.LCD_FUNCTION) 
205        sleep_ms(1) 
206        LcdApi.__init__(self, num_lines, num_columns) 
207        cmd = self.LCD_FUNCTION 
208        if num_lines > 1: 
209            cmd |= self.LCD_FUNCTION_2LINES 
210        self.hal_write_command(cmd) 
211    def hal_write_init_nibble(self, nibble): 
212        """Writes an initialization nibble to the LCD. 
213        This particular function is only used during initialization. 
214        """ 
215        byte = ((nibble >> 4) &s; 0x0f) << SHIFT_DATA 
216        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
217        self.i2c.writeto(self.i2c_addr, bytearray([byte])) 
218    def hal_backlight_on(self): 
219        """Allows the hal layer to turn the backlight on.""" 
220        self.i2c.writeto(self.i2c_addr, bytearray([1 << SHIFT_BACKLIGHT])) 
221    def hal_backlight_off(self): 
222        """Allows the hal layer to turn the backlight off.""" 
223        self.i2c.writeto(self.i2c_addr, bytearray([0])) 
224    def hal_write_command(self, cmd): 
225        """Writes a command to the LCD. 
226        Data is latched on the falling edge of E. 
227        """ 
228        byte = ((self.backlight << SHIFT_BACKLIGHT) | (((cmd >> 4) &s; 0x0f) << SHIFT_DATA)) 
229        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
230        self.i2c.writeto(self.i2c_addr, bytearray([byte])) 
231        byte = ((self.backlight << SHIFT_BACKLIGHT) | ((cmd &s; 0x0f) << SHIFT_DATA)) 
232        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
233        self.i2c.writeto(self.i2c_addr, bytearray([byte])) 
234        if cmd <= 3: 
235            # The home and clear commands require a worst case delay of 4.1 msec 
236            sleep_ms(5) 
237    def hal_write_data(self, data): 
238        """Write data to the LCD.""" 
239        byte = (MASK_RS | (self.backlight << SHIFT_BACKLIGHT) | (((data >> 4) &s; 0x0f) << SHIFT_DATA)) 
240        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
241        self.i2c.writeto(self.i2c_addr, bytearray([byte])) 
242        byte = (MASK_RS | (self.backlight << SHIFT_BACKLIGHT) | ((data &s; 0x0f) << SHIFT_DATA)) 
243        self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E])) 
244        self.i2c.writeto(self.i2c_addr, bytearray([byte]))

Credits And References

  1. Purchase your Gorillacell ESP32 development kit at: https://gorillacell.kr/

  2. YX5300 datasheet: http://geekmatic.in.ua/pdf/Catalex_MP3_board.pdf



Posts in this series



No comments yet!

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