风筝
发表于: 2020-2-3 12:46:00 | 显示全部楼层

对于Arduino微控制器来说,KY-023(或KY-23)是一款非常易于使用的模拟操纵杆模块。它具有二维数值(x和y轴)以及按下操纵杆时的按键状态。在本篇文章中,我们将主要介绍如何将KY-023操纵杆与Arduino进行连接以及如何使用它。


所需的材料清单:

–  Arduino Uno开发板

–  跳线

–  KY-023模拟操纵杆模块


通常,KY-023模块带有5个引脚排针:

●    GND(地线)

●    + 5V(5V引脚)

●    VRX(与x轴成比例的电压)

●    VRY(与y轴成比例的电压)

●    SW(按下操纵杆的引脚)

ky023_analog_joystick.jpg


如何将KY-023连接到Arduino?

将KY-023连接到Arduino非常简单。模块的“ GND”必须连接到Arduino的“ GND”。由于KY-023的工作电压也为5伏,因此模块的“ + 5V”可以直接连接到Arduino的任意“ 5V”引脚。

操纵杆实际上是两个电位器的组合。这意味着,当操纵杆沿x轴移动时,电阻会发生变化,从而导致电压发生变化。通过将VRX引脚连接到Arduino的模拟输入端,该电压可用于检测操纵杆的x位置。 y轴也是如此。通过将VRY连接到模拟输入,可以读取y轴的位置。在本文中,VRX连接到“ A0”,VRY连接到“ A1”。最后,SW连接到Arduino的数字引脚“ 2”。

scheme_ky023_arduino.jpg

将KY-023连接到Arduino Uno的连接原理图。

image_ky023_arduino_uno.jpg

KY-023连接到Arduino Uno的实物图。


如何使用Arduino IDE编程KY-023?

源代码非常简单。首先,我们设置两个模拟引脚A0和A1,以及数字引脚“ 2”,以检测操纵杆是否被按下。接下来,我们设置串口连接,该串口连接用于在控制台上打印出模拟操纵杆的当前状态。


然后,我们读取x轴和y轴的模拟数据。然后,将电位器的模拟电压映射到0到1023之间的数字值。如果如上示意图所示设置按钮,则将操纵杆向左移动到最左端,x值为0。如果将按钮向右移动,则x值最大为1023。如果将操纵杆上移至顶部,则y值为0。如果将操纵杆向下移,则y值为1023。


按钮的引脚模式(用于检测操纵杆是否被按下)使用上拉电阻。如果按下按钮,则引脚的值为0。因此,在源代码中使用了变量名“ notPressed”。

  1. const int inX = A0; // analog input for x-axis
  2. const int inY = A1; // analog input for y-axis
  3. const int inPressed = 2; // input for detecting whether the joystick/button is pressed
  4. int xValue = 0; // variable to store x value
  5. int yValue = 0; // variable to store y value
  6. int notPressed = 0; // variable to store the button's state => 1 if not pressed
  7. void setup() {
  8.   pinMode(inX, INPUT); // setup x input
  9.   pinMode(inY, INPUT); // setup y input
  10.   pinMode(inPressed, INPUT_PULLUP); // we use a pullup-resistor for the button functionality
  11.   
  12.   Serial.begin(9600); // Setup serial connection for print out to console
  13. }
  14. void loop() {
  15.   xValue = analogRead(inX); // reading x value [range 0 -> 1023]
  16.   yValue = analogRead(inY); // reading y value [range 0 -> 1023]
  17.   notPressed = digitalRead(inPressed); // reading button state: 1 = not pressed, 0 = pressed
  18.   
  19.   // print out values
  20.   Serial.print("X: ");
  21.   Serial.println(xValue);
  22.   Serial.print("Y: ");
  23.   Serial.println(yValue);
  24.   Serial.print("Not pressed: ");
  25.   Serial.println(notPressed);
  26.   
  27.   // The following delay of 1000ms is only for debugging reasons (it's easier to follow the values on the serial monitor)
  28.   delay(1000); // Probably not needed for most applications
  29. }
复制代码

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

本版积分规则

主题 700 | 回复: 1480



手机版|

GMT+8, 2024-4-27 07:39 , Processed in 0.039060 second(s), 6 queries , Gzip On, MemCache On. Powered by Discuz! X3.5

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

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