I have a question regarding controlling my LCD1602 with my Raspberry Pi 5. To do this I am using the smbus2 library. Here is my code that uses the smbus library to control the i2c system:
try: import smbus2 LCD = smbus2.SMBus(1) address = 0x27 IR = 0 DR = 1 ASCII_WORD = "HELLO" LCD.write_byte_data(address, IR, 0x80, force=None) #set the cursor at the beginning of line 1 for char in ASCII_WORD: LCD.write_byte_data(address, IR, 0x10, force=None) #set the cursor 1 column left for bit in range(8): LCD.write_byte_data(address, DR, ord(char) >> (7 - bit), force=None)#write ASCII character except KeyboardInterrupt: LCD.write_byte_data(address, IR, 0x01, force=None)#clear display LCD.close() Here is a great link in which I received most of the data bit values from: https://www.electronicsforu.com/technology-trends/learn-electronics/16x2-lcd-pinout-diagram
This is what is going on in my code:
- Set the cursor position.
- Write the ASCII of the character I want.
Issue:
The result from this code was unexpected, the cursor position was on the 5th column of the second row and there was a ≣ sign on the first row second column. I soon realised that the for bit in range(8): was unnecessary because the smbus2 library handles converting the decimal values to binary and sending that bit by bit (Please correct me if I’m wrong). This extra loop is likely causing duplicates of ASCII codes.
Debugged code:
try: import time import smbus2 LCD = smbus2.SMBus(1) address = 0x27 IR = 0 DR = 1 ASCII_WORD = "HELLO" LCD.write_byte_data(address, IR, 0x80, force=None) #set the cursor at the beginning of line 1 for char in ASCII_WORD: LCD.write_byte_data(address, IR, 0x10, force=None) #set the cursor 1 column left LCD.write_byte_data(address, DR, ord(char) >> (7 - bit), force=None)#write ASCII character except KeyboardInterrupt: LCD.write_byte_data(address, IR, 0x01, force=None)#clear display LCD.close() New Issue:
This code creates an issue where the whole LCD backlight turns off. It could be that the whole LCD turns off, but the power LED stays on.
Debugging:
I tried removing the except block as I thought maybe it was just clearing the display - the backlight was still turning off when I ran the code. I also tried isolating each LCD.write_byte_data() to see if one singular one was causing the issue - each isolated one was causing the backlight to turn off.
Could anyone please help me to debug these issues, specifically why the LCD is turning off via the second code and not turning off with the first one? I would really appreciate some help. Thank you in advance.