树莓派管脚图

使用Adafruit_Python_CharLCD库操作LCD1602前,需要做的准备工作:
配置树莓派使能i2c:

1
sudo raspi-config

安装i2c-tools检索i2c设备:

1
sudo apt-get install i2c-tools

确保i2c设备连上之后,检索i2c设备:

1
2
pi@raspberrypi ~ $ sudo i2cdetect -y 1
Error: Could not open file `/dev/i2c-1' or `/dev/i2c/1': No such file or directory

这里出现了问题,找不到i2c设备,原因是没有加载设备,执行以下命令:

1
sudo modprobe i2c-dev

如果要永久载入设备,需要修改文件/etc/modules加入i2c-dev这一行。
关于设备载入的配置详见:I2C设备载入和速率设置
由于linux下设备即时文件,同样可使用命令ls /dev | grep i2c来查看设备有没有加载。

下载和安装Adafruit_Python_CharLCD库:

1
2
3
4
git clone https://github.com/adafruit/Adafruit_Python_CharLCD.git
cd Adafruit_Python_CharLCD
sudo apt-get install python-dev
sudo python3 setup.py install

作业题目:
按顺序(GREEN,RED,CYAN,BLUE,YELLOW),间隔1秒点亮RGB,同时保持LCD显示正确。

方法1,简单暴力的写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/python3
# Example using a character LCD plate.
import time
import Adafruit_CharLCD as LCD

# Initialize the LCD using the pins
lcd = LCD.Adafruit_CharLCDPlate()

print('Press Ctrl-C to quit.')
while True:
lcd.set_color(0.0, 1.0, 0.0)
lcd.clear()
lcd.message('GREEN')
time.sleep(1.0)

lcd.set_color(1.0, 0.0, 0.0)
lcd.clear()
lcd.message('RED')
time.sleep(1.0)

lcd.set_color(0.0, 1.0, 1.0)
lcd.clear()
lcd.message('CYAN')
time.sleep(1.0)

lcd.set_color(0.0, 0.0, 1.0)
lcd.clear()
lcd.message('BLUE')
time.sleep(1.0)

lcd.set_color(1.0, 1.0, 0.0)
lcd.clear()
lcd.message('YELLOW')
time.sleep(1.0)

方法2,易扩展的写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/usr/bin/python3
import time
import Adafruit_CharLCD as LCD

color_dicts = {'GREEN': (0.0, 1.0, 0.0),
'RED': (1.0, 0.0, 0.0),
'CYAN': (0.0, 1.0, 1.0),
'BLUE': (0.0, 0.0, 1.0),
'YELLOW': (1.0, 1.0, 0.0)
}

def animation(color, seconds):
lcd = LCD.Adafruit_CharLCDPlate()
if color in color_dicts:
rgb = color_dicts.get(color)
lcd.set_color(rgb[0], rgb[1], rgb[2])
lcd.clear()
lcd.message(color)
time.sleep(seconds)

if __name__ == '__main__':
print('Press Ctrl-C to quit.')
colors = ['GREEN', 'RED', 'CYAN', 'BLUE', 'YELLOW']
while True:
for color in colors:
animation(color, 1)

执行Python程序:

1
./char_LCD_animation.py

这种执行方法需要在Python程序的第一行写上#!/usr/bin/python3,而且需要Python程序文件拥有可执行的属性。

效果:
树莓派LCD动画

说明:
我这里的显示颜色和对应的文字不一样,原因可能是在淘宝上买的模块的硬件的LED灯连线是错误的,官方的例子运行起来颜色对应也不正确。