| 对于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(按下操纵杆的引脚) 
  
 如何将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”。 
  将KY-023连接到Arduino Uno的连接原理图。 
  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”。 复制代码const int inX = A0; // analog input for x-axis
const int inY = A1; // analog input for y-axis
const int inPressed = 2; // input for detecting whether the joystick/button is pressed
int xValue = 0; // variable to store x value
int yValue = 0; // variable to store y value
int notPressed = 0; // variable to store the button's state => 1 if not pressed
void setup() {
  pinMode(inX, INPUT); // setup x input
  pinMode(inY, INPUT); // setup y input
  pinMode(inPressed, INPUT_PULLUP); // we use a pullup-resistor for the button functionality
  
  Serial.begin(9600); // Setup serial connection for print out to console
}
void loop() {
  xValue = analogRead(inX); // reading x value [range 0 -> 1023]
  yValue = analogRead(inY); // reading y value [range 0 -> 1023]
  notPressed = digitalRead(inPressed); // reading button state: 1 = not pressed, 0 = pressed
  
  // print out values
  Serial.print("X: ");
  Serial.println(xValue);
  Serial.print("Y: ");
  Serial.println(yValue);
  Serial.print("Not pressed: ");
  Serial.println(notPressed);
  
  // The following delay of 1000ms is only for debugging reasons (it's easier to follow the values on the serial monitor)
  delay(1000); // Probably not needed for most applications
}
 |