라즈베리파이로 LCD 사용하기

상현·2022년 11월 25일
1
post-thumbnail


해당 LCD는 2행 16열의 문자를 입력할 수 있다. 원래는 전면부의 pin 16개를 통해 제어해야하지만 해당 모듈은 뒤에서 I2C제어를 가능하게 해주는 모듈이 달려있다.


LCD 1602Raspberry Pi 4
GND39
VCC2
SDA3
SCL5

RC-522때 SPI를 enable했듯이, 해당 모듈을 사용하려면 I2C를 enable해줘야 한다.

pip install smbus2

smbus2를 설치하고

#!/usr/bin/env python3
import LCD1602
import time

def setup():
    LCD1602.init(0x3f, 1)
    LCD1602.write(0, 0, 'Hello World!!')
    LCD1602.write(5, 1, '- RPi 400 -')
    time.sleep(2)

def destroy():
    pass

if __name__ == "__main__":
    try:
        setup()
        while True:
            pass
    except KeyboardInterrupt:
        destroy()

의 기본 코드와

#!/usr/bin/env python3

import time
import smbus2 as smbus

BUS = smbus.SMBus(1)

def write_word(addr, data):
	global BLEN
	temp = data
	if BLEN == 1:
		temp |= 0x08
	else:
		temp &= 0xF7
	BUS.write_byte(addr ,temp)

def send_command(comm):
	# Send bit7-4 firstly
	buf = comm & 0xF0
	buf |= 0x04               # RS = 0, RW = 0, EN = 1
	write_word(LCD_ADDR ,buf)
	time.sleep(0.002)
	buf &= 0xFB               # Make EN = 0
	write_word(LCD_ADDR ,buf)

	# Send bit3-0 secondly
	buf = (comm & 0x0F) << 4
	buf |= 0x04               # RS = 0, RW = 0, EN = 1
	write_word(LCD_ADDR ,buf)
	time.sleep(0.002)
	buf &= 0xFB               # Make EN = 0
	write_word(LCD_ADDR ,buf)

def send_data(data):
	# Send bit7-4 firstly
	buf = data & 0xF0
	buf |= 0x05               # RS = 1, RW = 0, EN = 1
	write_word(LCD_ADDR ,buf)
	time.sleep(0.002)
	buf &= 0xFB               # Make EN = 0
	write_word(LCD_ADDR ,buf)

	# Send bit3-0 secondly
	buf = (data & 0x0F) << 4
	buf |= 0x05               # RS = 1, RW = 0, EN = 1
	write_word(LCD_ADDR ,buf)
	time.sleep(0.002)
	buf &= 0xFB               # Make EN = 0
	write_word(LCD_ADDR ,buf)

def init(addr, bl):
#	global BUS
#	BUS = smbus.SMBus(1)
	global LCD_ADDR
	global BLEN
	LCD_ADDR = addr
	BLEN = bl
	try:
		send_command(0x33) # Must initialize to 8-line mode at first
		time.sleep(0.005)
		send_command(0x32) # Then initialize to 4-line mode
		time.sleep(0.005)
		send_command(0x28) # 2 Lines & 5*7 dots
		time.sleep(0.005)
		send_command(0x0C) # Enable display without cursor
		time.sleep(0.005)
		send_command(0x01) # Clear Screen
		BUS.write_byte(LCD_ADDR, 0x08)
	except:
		return False
	else:
		return True

def clear():
	send_command(0x01) # Clear Screen

def openlight():  # Enable the backlight
	BUS.write_byte(0x27,0x08)
	BUS.close()

def write(x, y, str):
	if x < 0:
		x = 0
	if x > 15:
		x = 15
	if y <0:
		y = 0
	if y > 1:
		y = 1

	# Move cursor
	addr = 0x80 + 0x40 * y + x
	send_command(addr)

	for chr in str:
		send_data(ord(chr))

if __name__ == '__main__':
	init(0x27, 1)
	write(4, 0, 'Hello')
	write(7, 1, 'world!')

의 LCD1602.py를 작성해야 한다. 나는 해당 모듈을 Sunfounder에서 구매했기에
https://github.com/sunfounder/SunFounder_SensorKit_for_RPi2/tree/master/Python
에서 LCD1602.py를 사용했다.

해당 코드를 실행하면

아래와 같은 출력 결과를 얻을 수 있다.

0개의 댓글