LCD即我们常见的液晶显示屏,通过LCD我们可以有效并即时的获取Arduino的信息。本篇中选用的LCD为常见的1062字符型LCD,同时需要一块 IIC-LCD 转接板,如果没有的话也可以实现,连线稍微复杂一些。而通过转接版将能够节约4个端口。
在此篇中我们将用到IIC通信协议,在不同的Arduino主板上,IIC通信协议的端口略有不同:
Board I2C / TWI pins
Uno, Ethernet A4 (SDA), A5 (SCL)
Mega2560 20 (SDA), 21 (SCL)
Leonardo 2 (SDA), 3 (SCL)
Due 20 (SDA), 21 (SCL), SDA1, SCL1
SLC为时钟信号,SDA为数据信号。转接板背面如图:
根据自己的arduino版本找到对应的SDA、SCL端口,DAT连接SDA,CLK连接SCL,注意DAT端口右侧的螺丝,是一个可调电位器,用于调整LCD显示,以显示出清晰的图片。
Mega加上传感器扩展板后的接线如图,红黑为正负,白线为数据线,棕线为时钟线
连接完毕,通电,烧入如下代码,这里使用的是LiquidCrystal库中的demo。将其拷贝指ArduinoIDE的library文件夹下,在IDE的File-> Examples 中找到LiquidCrystal 打开其中的 Hello Word I2c 范例
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 | #include "Wire.h" #include "LiquidCrystal.h" // Connect via i2c, default address #0 (A0-A2 not jumpered) LiquidCrystal lcd(0); void setup() { // set up the LCD's number of rows and columns: lcd.begin(16, 2); // Print a message to the LCD. lcd.print("hello, world!"); } void loop() { // set the cursor to column 0, line 1 // (note: line 1 is the second row, since counting begins with 0): lcd.setCursor(0, 1); // print the number of seconds since reset: lcd.print(millis()/1000); lcd.setBacklight(HIGH); delay(500); lcd.setBacklight(LOW); delay(500); } |
此段代码的效果如同
LCD板显示hello,world的同时,输出计时秒数并闪烁屏幕。
这里简单介绍一下LiquidCrystal库的基本用法:
begin()
此函数带有两个参数 意为 set up the LCD’s number of columns and rows,即初始化led的显示区域的大小
print()
Prints text to the LCD.
在LCD屏幕上显示打印
clear()
清屏
home()
将输出光标定位到初始位置(左上角)
setCursor()
lcd.setCursor(col, row) 设置光标位置
write()
输出,类似于print
cursor()/nocursor()
显示/隐藏光标
blink()/noblink()
光标处是否闪烁
autoscroll()/noAutoscroll()
是否自动滚动
以上为LiquidCrystal库的主要函数,这里上传了一个LiquidCrystal库包(点击下载LiquidCrystal)。
通过LiquidCrystal库对LCD的操作,我们可以在Arduino上实时进行数据打印,而不再需要串口监听。
例如,做了一个简单的超声波测距显示,超声波模块的代码在之前几篇中已经实现,现修改程序如下
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 | #include "Wire.h" #include "LiquidCrystal.h" LiquidCrystal lcd(0); const int TrigPin = 3; const int EchoPin = 2; long distance; void setup() { pinMode(TrigPin, OUTPUT); pinMode(EchoPin, INPUT); lcd.begin(16, 2); lcd.setBacklight(HIGH); } void loop() { digitalWrite(TrigPin, HIGH); delayMicroseconds(10); digitalWrite(TrigPin, LOW); distance = pulseIn(EchoPin, HIGH)/58; lcd.setCursor(0, 0); lcd.clear(); lcd.print(distance); lcd.print("cm"); delay(1000); } |
运行效果如图
今天就到这里吧,谢谢关注。
BeiTown
2013.03.28