1.水哥学习arduino系列之按键开关lcd背光
quan 编辑于2025-03-06 20:33arduino学习
第一次学习arduino硬件中断,做了个开关,可以用按键控制lcd背光。用的是i2c的接口,所以调用了LiquidCrystal_I2C.h的库。我这里用了i2c接在后面,四个接口由上到下分别是:GND,VCC,SDA,SCL。分别插在arduinoUNO板上。我这里的lcd电压是3.3v的,如果您的lcd是5v的,就接在旁边的5v的接口上,否则会损坏lcd和arduinoUNO板。
硬件
源码
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define BUTTON_PIN 2
int target_backlightState = false;
int current_backlightState = false;
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
void setup()
{
pinMode(BUTTON_PIN,INPUT_PULLUP);
lcd.init(); // initialize the lcd
// Print a message to the LCD.
lcd.setCursor(0,0);
lcd.print("Welcome to the");
lcd.setCursor(0,1);
lcd.print("Arduino world!");
attachInterrupt(0, press_isr, FALLING);
}
void press_isr(){
target_backlightState = !target_backlightState;
}
void loop()
{
if (target_backlightState != current_backlightState) {
if(current_backlightState){
lcd.noBacklight();
current_backlightState = false;
}//if
else{
lcd.backlight();
current_backlightState = true;
}//else
}//if
}//loop
这个代码已经完成了开关lcd背光的功能,但测试了一下,偶尔没有响应,原来是按键抖动,就查了一下按键消抖,安装了bounce2库来解决按键抖动的问题。
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Bounce2.h>
#define BUTTON_PIN 2
Bounce2::Button button = Bounce2::Button();
int target_backlightState = false;
int current_backlightState = false;
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
void setup()
{
button.attach( BUTTON_PIN, INPUT ); // USE EXTERNAL PULL-UP
button.interval(5); // DEBOUNCE INTERVAL IN MILLISECONDS
button.setPressedState(LOW); // INDICATE THAT THE LOW STATE CORRESPONDS TO PHYSICALLY PRESSING THE BUTTON
pinMode(BUTTON_PIN,INPUT_PULLUP);
lcd.init(); // initialize the lcd
// Print a message to the LCD.
lcd.setCursor(0,0);
lcd.print("Welcome to the");
lcd.setCursor(0,1);
lcd.print("Arduino world!");
attachInterrupt(0, press_isr, FALLING);
}
void press_isr(){
target_backlightState = !target_backlightState;
}
void loop()
{
/*if (target_backlightState != current_backlightState) {
if(current_backlightState){
lcd.noBacklight();
current_backlightState = false;
}//if
else{
lcd.backlight();
current_backlightState = true;
}//else
}//if
*/
button.update();
if(button.pressed()){
if(current_backlightState){
lcd.noBacklight();
current_backlightState = false;
}//if
else{
lcd.backlight();
current_backlightState = true;
}//else
}//if
}//loop
因为lcd默认的背光太亮,而且软件无法调节背光亮度,我就把开启背光的跳线帽换成了一个1k欧的电阻。
实验结果
关于本站
肥龙软件分享的软件是本站作者开发的免费,无广告,安全可靠,绝不附带任何无关软件,绝不困绑任何插件的实用软件。如果您感觉好用,可以捐赠我们,这样我们可以有更积极的动力去改进升级软件,维持服务器运转,感谢您的捐助,谢谢!
联系作者(邮箱)
软件