一、學習目標:學習使用I2C 2X16 lcd
i2c為一種通訊界面,2x16代表lcd為二行,每行可以顯示16個字母。
二、接線圖
SDA – 接 Arduino 的 Analog Pin 4 (Arduino Mega 為 Pin 20)
SCL – 接 Arduino 的 Analog Pin 5 (Arduino Mega 為 Pin 21)
GND – 接 GND
VCC – 接 +5V
三、參考資料:
http://coopermaa2nd.blogspot.tw/2012/09/i2c-16x2-lcd.html
四、程式碼
練習一:如何每秒測量一次,利出
- #include <Wire.h>
- #include <LiquidCrystal_I2C.h>
- LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
- void setup()
- {
- lcd.init(); // initialize the lcd
- // Print a message to the LCD.
- lcd.backlight();
- lcd.setCursor(1, 0);//第1列,空1格開始
- lcd.print("Hello, world!");
- lcd.setCursor(2, 1);//第2列,空2格開始
- lcd.print("second line");
- }
- void loop()
- {
- }
五、作業:
- #include <Wire.h>
- #include <LiquidCrystal_I2C.h>
- // set the LCD address to 0x27 for a 16 chars and 2 line display
- LiquidCrystal_I2C lcd(0x27,16,2);
- int no=0;//計數器
- void setup()
- {
- lcd.init(); // initialize the lcd
- // Print a message to the LCD.
- lcd.backlight();
- lcd.setCursor(1, 0);//第1列,空1格開始
- lcd.print("Hello, world!");
- lcd.setCursor(2, 1);//第2列,空2格開始
- lcd.print("sceond line");
- delay(3000);//等3秒
- }
- void loop(){
- no++;
- //資料顯示在LCD
- lcd.setCursor(0, 0);
- lcd.print("No.");
- lcd.print(no);
- delay(500); //每500ms更新一次
- lcd.clear();
- }
如何將 HC-SR04 超聲波模組測量結果,以lcd顯示。
畫愛心的方法
- #include <Wire.h>
- #include <LiquidCrystal_I2C.h>
- LiquidCrystal_I2C lcd(0x27,16,2);
- int number=0;
- #define TrigPIN 13
- #define EchoPIN 12
- void setup() {
- pinMode(TrigPIN, OUTPUT);
- pinMode(EchoPIN, INPUT);
- lcd.init(); // initialize the lcd
- // Print a message to the LCD.
- lcd.backlight();
- lcd.setCursor(1, 0);//第1列,空1格開始
- lcd.print("Hello,HC_SR04!");
- //序列埠除錯用
- Serial.begin(9600);
- Serial.println("Hello, HC_SR04!");
- delay(1000);
- }
- void loop() {
- float duration, distance;//時間、距離
- digitalWrite(TrigPIN, HIGH);
- delayMicroseconds(1000);
- digitalWrite(TrigPIN, LOW);
- duration = pulseIn (EchoPIN, HIGH);//pulseIn ( ) :讀取一個針腳的脈衝時間(HIGH或LOW)
- distance = (duration/2)/29;
- number = number +1;
- lcd.setCursor (0,0);
- lcd.print("No.");
- lcd.print (number);
- lcd.setCursor(0, 1);
- lcd.print ("Dis.");
- lcd.print(distance);
- lcd.print ("cm");
- Serial.print("No.");
- Serial.print (number);
- Serial.print (" Dis. ");
- Serial.print(distance);
- Serial.println (" cm");//換行
- delay(1000);
- lcd.clear();
- }
- #include <Wire.h>
- #include <LiquidCrystal_I2C.h>
- LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x27 for a 16 chars and 2 line display
- #if defined(ARDUINO) && ARDUINO >= 100
- #define printByte(args) write(args);
- #else
- #define printByte(args) print(args,BYTE);
- #endif
- uint8_t heart[8] = {0x0,0xa,0x1f,0x1f,0xe,0x4,0x0};
- void setup() {
- Serial.begin(9600);
- lcd.init(); // initialize the lcd
- // Print a message to the LCD.
- lcd.backlight();
- lcd.createChar(0, heart);
- }
- void loop() {
- lcd.printByte(0);
- delay(1000);
- lcd.clear();
- }