Arduino中使用I2C通信可直接调用Wire.h库, 这个库允许Arduino链接其他I2C设备, 链接线有两条, 分别是SDA(数据行)和SCI(时钟线). 各型号Arduino的I2C对应引脚:
Arduino Board:I2C / TWI pins
Arduino Uno/Ethernet:A4 (SDA), A5 (SCL)
Arduino Mega2560:20 (SDA), 21 (SCL)
Arduino Leonardo:2 (SDA), 3 (SCL)
Arduino Due:20 (SDA), 21 (SCL), SDA1, SCL1
一般购买到的是分开的两个组件, 需要按下图这样将PCF8574T焊接到1602LCD上
PCF8574T模块4pin(Gnd, Vcc, SDA i2c数据, SCL i2c时钟)和Arduino接口的对应关系: Gnd -> Gnd, Vcc -> Vcc, SDA -> A4, SDL -> A5
获取I2C地址
#include <Wire.h> void setup() { Serial.begin (115200); // Leonardo: wait for serial port to connect while (!Serial) { } Serial.println (); Serial.println ("I2C scanner. Scanning ..."); byte count = 0; Wire.begin(); for (byte i = 8; i < 120; i++) { Wire.beginTransmission (i); if (Wire.endTransmission () == 0) { Serial.print ("Found address: "); Serial.print (i, DEC); Serial.print (" (0x"); Serial.print (i, HEX); Serial.println (")"); count++; delay (1); // maybe unneeded? } // end of good response } // end of for loop Serial.println ("Done."); Serial.print ("Found "); Serial.print (count, DEC); Serial.println (" device(s)."); } // end of setup void loop() {}
运行时, 打开Serial Monitor, 将波特率设为115200, 看到的输出就是I2C地址
自带LiquidCrystal_I2C显示测试
在运行显示测试前检查是否已经安装了library: LiquidCrystal, LiquidCrystal_I2C
#include <Wire.h> #include <LiquidCrystal_I2C.h> // I2C地址, 一般为0x3F, 0x20或0x27 LiquidCrystal_I2C lcd(0x27,16,2); void setup() { lcd.init(); lcd.backlight(); // 打开背光 } void loop() { lcd.setCursor(0,0); lcd.print("LCD1602 iic Test"); lcd.setCursor(0,1); lcd.print("0123456789ABCDEF"); delay(1000); }
如果屏幕亮但是无显示, 可以调节背后的电位器让字符显示到合适的对比度.
第三方New LiquidCrystal显示测试
到 https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads/ 下载最新的library并安装
#include <Wire.h> #include <LCD.h> #include <LiquidCrystal_I2C.h> LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7); // 0x27 is the I2C bus address for an unmodified backpack void setup() { // activate LCD module lcd.begin (16,2); // for 16 x 2 LCD module lcd.setBacklightPin(3,POSITIVE); lcd.setBacklight(HIGH); } void loop() { lcd.home (); // set cursor to 0,0 lcd.print("HELLO WORLD...."); lcd.setCursor (0,1); // go to start of 2nd line lcd.print(millis()); delay(1000); lcd.setBacklight(LOW); // Backlight off delay(1000); lcd.setBacklight(HIGH); // Backlight on }
供电和耗电测试
硬件是Arduino NANO + 扩展板 + PCF8574T + 1602LCD, 使用输入电压12V. 扩展板本身不带IC, 只有一个电源LED, 功耗可以忽略. 在使用自带的LiquidCrystal_I2C库跑上面的测试代码时, 测得的功耗仅为0.95W左右.