如何用两个按键控制lcd1602的两行,按键1按下只显示第一行内容,按键2按下只显示第二行内容
1、包含必要的头文件。需要包含以下头文件,以便使用 LCD 1602 的函数:
#include <LiquidCrystal.h>
#include <Keypad.h>
2、定义 LCD 1602 和按键。需要定义 LCD 1602 和按键的引脚,以便可以将它们连接到微控制器上:
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
3、初始化 LCD 1602。在初始化 LCD 1602 之前,需要先将其设置为所需的参数。这可以通过调用 lcd.begin() 函数来实现:
lcd.begin(16, 2);
4、设置 LCD 1602 的内容。可以使用 lcd.setCursor() 和 lcd.print() 函数来设置 LCD 1602 的内容:
lcd.setCursor(0, 0);
lcd.print("Line 1");
lcd.setCursor(0, 1);
lcd.print("Line 2");
5、处理按键输入。可以使用keypad.getKey() 函数来处理按键输入,并根据按键的值来控制 LCD 1602 的显示:
char key = keypad.getKey();
if (key == '1') {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Line 1");
} else if (key == '2') {
lcd.clear();
lcd.setCursor(0, 1);
lcd.print("Line 2");
}
可以在循环中使用这些函数,以便持续监视按键的输入并控制 LCD 1602 的显示。
仅供参考,望采纳。
望采纳!!点击该回答右侧的“采纳”按钮即可采纳!!
我使用Arduino语言来控制LCD1602显示屏,代码如下:
#include <LiquidCrystal.h>
// 定义按键1和按键2的引脚
const int button1Pin = 2;
const int button2Pin = 3;
// 定义LCD显示屏的引脚
const int rs = 7, en = 8, d4 = 9, d5 = 10, d6 = 11, d7 = 12;
// 创建LCD显示屏对象
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
// 定义显示的文本内容
const String line1 = "Line 1";
const String line2 = "Line 2";
// 初始化变量
int button1State = 0;
int button2State = 0;
bool showLine1 = true;
void setup() {
// 初始化按键1和按键2为输入模式
pinMode(button1Pin, INPUT);
pinMode(button2Pin, INPUT);
// 初始化LCD显示屏,设置为16列,2行
lcd.begin(16, 2);
}
void loop() {
// 读取按键1和按键2的状态
button1State = digitalRead(button1Pin);
button2State = digitalRead(button2Pin);
// 当按键1被按下时,只显示第一行内容
if (button1State == LOW) {
lcd.clear();
lcd
.setCursor(0, 0);
lcd.print(line1);
showLine1 = true;
}
// 当按键2被按下时,只显示第二行内容
if (button2State == LOW) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(line2);
showLine1 = false;
}
// 当两个按键都没有被按下时,显示两行内容
if (button1State == HIGH && button2State == HIGH && showLine1 == true) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(line1);
lcd.setCursor(0, 1);
lcd.print(line2);
}
if (button1State == HIGH && button2State == HIGH && showLine1 == false) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(line2);
lcd.setCursor(0, 1);
lcd.print(line1);
}
// 延迟500毫秒
delay(500);
}