# 液晶顯示LCD1602

## 一、直接使用GPIO模式

要把樹莓派感測的資料顯示出來，比如溫度溼度等等，除了先前介紹的七節LED或是矩陣LED外，LCD1602是最常用的顯示模組，因為物美價廉且行之多年，要使用它有二種方法，先介紹直接使用GPIO的模式。

首先看一下它的接腳說明：其實真正使用的是上圖黃色的腳位，不要被16個腳位嚇到了

![](/files/-LdYyZw8dLpgMgJKycO7)

使用的Python Package 為 <https://github.com/dbrgn/RPLCD>

參考網站一：<http://www.circuitbasics.com/raspberry-pi-lcd-set-up-and-programming-in-python/>

參考網站二：<https://www.raspberrypi-spy.co.uk/2012/07/16x2-lcd-module-control-using-python/>

{% embed url="<https://youtu.be/_71grpf0YJk>" %}

```python
from RPLCD.gpio import CharLCD
import RPi.GPIO as GPIO
import time

lcd = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23], numbering_mode=GPIO.BOARD)

lcd.clear()
lcd.home()
lcd.write_string('Hello World\r\nMy Name is Wooss')
time.sleep(3)
lcd.clear()

for i in range(10):
    lcd.cursor_pos = (0, 0)
    lcd.write_string("Time: %s" % time.strftime("%H:%M:%S"))
    print("Time: %s" % time.strftime("%H:%M:%S"))
    print("Date: %s" % time.strftime("%m/%d/%Y"))
    lcd.cursor_pos = (1, 0)
    lcd.write_string("Date: %s" % time.strftime("%m/%d/%Y"))
    time.sleep(1)

framebuffer = [
    '',
    '',
]


def write_to_lcd(lcd, framebuffer, num_cols):
    lcd.home()
    for row in framebuffer:
        lcd.write_string(row.ljust(num_cols)[:num_cols])
        lcd.write_string('\r\n')

lcd.clear()
lcd.home()
write_to_lcd(lcd, framebuffer, 16)

long_string = 'This string is too long to fit'


def loop_string(string, lcd, framebuffer, row, num_cols, delay=0.3):
    padding = ' ' * num_cols
    s = padding + string + padding
    for i in range(len(s) - num_cols + 1):
        framebuffer[row] = s[i:i + num_cols]
        write_to_lcd(lcd, framebuffer, num_cols)
        time.sleep(delay)


while True:
    loop_string(long_string, lcd, framebuffer, 0, 16)

# GPIO.cleanup()

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://s761111.gitbook.io/raspi-sensor/ye-jing-shi-lcd1602.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
