风筝
发表于: 2018-8-14 09:47:12 | 显示全部楼层

键盘允许用户在程序运行时输入数据。本篇文章主要介绍如何将一个带有十二个按键的键盘连接到Arduino开发板以及如何使用库Keypad.h。


通常需要键盘来为Arduino开发板提供输入信号,而薄膜键盘是许多应用的经济型解决方案。它们非常薄,可以轻松安装在任何需要的地方。


在本篇文章中,我们将演示如何使用12键数字键盘,类似于电话上的键盘。 12键键盘有三列四行。按下按钮会将其中一个行输出短接到其中一个列输出。根据这些信息,Arduino可以确定按下了哪个按键。例如,当按下1键时,列1和行1短接。 Arduino会检测到并向程序输入1。


在键盘内部行排列和列排列如下图所示。

keypad2.png


实验

对于这个实验,我们演示了Arduino库“keypad.h”。当用户按下键盘上的按键时,程序将在串口监视器显示该值。


需要的硬件

●    Arduino Mega 2560开发板

●    3x4矩阵键盘

●    连接导线

●    面包板


接线图

将键盘连接到Arduino,如下所示。

keypad_arduino.jpg


代码

  1. /* the tutorial code for 3x4 Matrix Keypad with Arduino is as
  2. This code prints the key pressed on the keypad to the serial port*/

  3. #include "Keypad.h"

  4. const byte Rows= 4; //number of rows on the keypad i.e. 4
  5. const byte Cols= 3; //number of columns on the keypad i,e, 3

  6. //we will definne the key map as on the key pad:

  7. char keymap[Rows][Cols]=
  8. {
  9. {'1', '2', '3'},
  10. {'4', '5', '6'},
  11. {'7', '8', '9'},
  12. {'*', '0', '#'}
  13. };

  14. //  a char array is defined as it can be seen on the above


  15. //keypad connections to the arduino terminals is given as:

  16. byte rPins[Rows]= {A6,A5,A4,A3}; //Rows 0 to 3
  17. byte cPins[Cols]= {A2,A1,A0}; //Columns 0 to 2

  18. // command for library forkeypad
  19. //initializes an instance of the Keypad class
  20. Keypad kpd= Keypad(makeKeymap(keymap), rPins, cPins, Rows, Cols);

  21. void setup()
  22. {
  23.      Serial.begin(9600);  // initializing serail monitor
  24. }

  25. //If key is pressed, this key is stored in 'keypressed' variable
  26. //If key is not equal to 'NO_KEY', then this key is printed out
  27. void loop()
  28. {
  29.      char keypressed = kpd.getKey();
  30.      if (keypressed != NO_KEY)
  31.      {
  32.           Serial.println(keypressed);
  33.      }
  34. }
复制代码

总结

这是一个非常简单的示例,您可以看到将键盘输入添加到Arduino程序中是多么容易。您可以将此类输入用于许多不同的项目,包括:

●    门锁

●    输入PWM

●    闹钟

●    安全锁

跳转到指定楼层
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题 700 | 回复: 1480



手机版|

GMT+8, 2024-4-20 08:14 , Processed in 0.126145 second(s), 6 queries , Gzip On, MemCache On. Powered by Discuz! X3.5

YiBoard一板网 © 2015-2022 地址:河北省石家庄市长安区高营大街 ( 冀ICP备18020117号 )

快速回复 返回顶部 返回列表