带两个轴(水平/垂直)和一个集成按钮的模拟操纵杆。
引脚名称
名字 | 描述 |
VCC | 正电源 |
VERT | 垂直轴输出(模拟) |
HORZ | 水平轴输出(模拟) |
SEL | 按钮 |
GND | 地 |
使用操纵杆与arduino的连接
操纵杆销 | 阿尔杜伊诺针 | 示例代码引脚 |
VCC | 5V | |
VERT/VRx | 任何模拟引脚 (A0...A5) | A0 |
HORZ /VRy | 任何模拟引脚 (A0...A5) | A1 |
SEL/SW | 任何数字引脚 | 2 |
GND | GND |
代码解析:
- 获取键值函数
xPosition = analogRead(VRx);
yPosition = analogRead(VRy);
SW_state = digitalRead(SW);
- 映射函数
mapX = map(xPosition, 0, 1023, -512, 512);
mapY = map(yPosition, 0, 1023, -512, 512);
①语法
map(value, fromLow, fromHigh, toLow, toHigh)
②参数
- value:要映射的号码。
- fromLow: 价值当前范围的下限。
- fromHigh: 值当前范围的上限。
- toLow: 价值目标范围的下限。
- toHigh:值目标范围的上限。
您可以使用map()功能将值重新映射到不同的范围。
例如map(analogRead(HORZ_PIN), 0, 1023, -100, 100),当操纵杆一直向右方向时,将返回 -100,当操纵杆处于中心位置时返回 0,当操纵杆向左返回时返回 100。
模拟器示例
点击此处joystick开始仿真
超链接插入不了,我们可以复制链接去试试仿真下↓↓↓
https://wokwi.com/arduino/projects/315483238220956225
源代码
/*
Joystick Module
created 18 Dec 2018
by MisterBotBreak
This example code can be found:
https://create.arduino.cc/projecthub/MisterBotBreak/how-to-use-a-joystick-with-serial-monitor-1f04f0
*/
int VRx = A0; //Analog Pin for X Position
int VRy = A1; //Analog Pin for Y Position
int SW = 7; //Digital Pin for Button
//Store State Variables
int xPosition = 0;
int yPosition = 0;
int SW_state = 0;
int mapX = 0;
int mapY = 0;
void setup() {
Serial.begin(9600);
pinMode(VRx, INPUT);
pinMode(VRy, INPUT);
pinMode(SW, INPUT_PULLUP);
}
void loop() {
//Read Data
xPosition = analogRead(VRx);
yPosition = analogRead(VRy);
SW_state = digitalRead(SW);
mapX = map(xPosition, 0, 1023, -512, 512);
mapY = map(yPosition, 0, 1023, -512, 512);
//Print Data in Serial Monitor - Find it at Tools > Serial Monitor
Serial.print("X: ");
Serial.print(mapX);
Serial.print(" | Y: ");
Serial.print(mapY);
Serial.print(" | Button: ");
Serial.println(SW_state);
delay(100);
}
结束
做一个简单的人,看得清世间繁杂却不在心中留下痕迹,保持平常心,简单,快乐。。