abuzcty 发表于 2017-7-22 22:54:36

4*4矩阵键盘和LCD1602液晶屏组合显示输入数字


最近写了一个用矩阵键盘输入数字,液晶屏显示的交互系统。
既可以输入整数,也可以输入小数,Arduino接受到的是一个double型变量。

矩阵键盘布局如下:
1 2 3 A
4 5 6 B
7 8 9 C
* 0 # D

程序用到了<LiquidCrystal.h><Keypad.h>两个官方ARDUINO库

主体程序如下(直接复制是不能用的,要配合你的接线情况更改,需要库文件的可以直接跳过程序部分):

unsigned char ch2num(char a)
{
        return a-'0';
}
double inputnum_sub()
{
        double numint = 0.0;
        lcd.setCursor(0,0);               
        char customKey = customKeypad.getKey();
        while(customKey != '.')
        {
                if(customKey == 'C')
                {
                        lcd.clear();
                        return 9999999.9;
                }
                if(customKey>='0' && customKey <= '9')
                {
                        numint = numint * 10 + ch2num(customKey);
                        lcd.print(customKey);                               
                }
                customKey = customKeypad.getKey();
        }
        lcd.print('.');
        double numfloat = 0.0;
        double n = 1.0;
        while(customKey != '#')
        {
                if(customKey == 'C')
                {
                        lcd.clear();
                        return 9999999.9;
                }
                if(customKey>='0' && customKey <= '9')
                {
                        numfloat = numfloat * 10 + ch2num(customKey);
                        lcd.print(customKey);
                        n = n * 10.0;               
                }
                customKey = customKeypad.getKey();
        }
        numfloat = numfloat / n;
        return numint+numfloat;
}
double inputnum()
{
        double a = 0.0;
        while((a = inputnum_sub()) > 1000000.0);
        return a;
}



使用时直接调用inputnum()函数即可
例如:

double a = inputnum();





以下很重要,想要用库的请注意看!!!!!


我用的是mega。其他板子请根据实际情况在库里更改接线。
接线:
矩阵键盘:行:40,38,36,34
                列:32,30,28,26
LCD1602:RS,E, D0,D1, D2, D3, D4, D5, D6, D7
                41, 39,37, 35, 33,31, 29,27, 25, 23

不会连钱的请去看基础教程。。。

说明:
输入必须有小数点,‘#’为确定。
例如:
你想输入1.2,按键顺序是:“1”,“.”,“2”,“#”,程序就会输出1.2
如果你想输入10,按键顺序是:“1”,“0”,”.“,”#“,程序就会输出10.0
如果你输错了,直接输入”C“,屏幕会清零,再重新输入即可。



maxims 发表于 2017-7-24 10:53:34

:victory:好。从来没有用过这个库

jasonwang1208 发表于 2017-7-24 11:06:36

3Q for sharing.

yangh2961 发表于 2017-8-5 12:31:50

你好楼主,您的这些代码我在实际使用的时候遇到点问题
页: [1]
查看完整版本: 4*4矩阵键盘和LCD1602液晶屏组合显示输入数字