双轴按键摇杆模块、电位器,使用详解
双轴按键摇杆模块
在 Arduino 中使用摇杆模块时,其实并没有专门针对摇杆模块的特定官方库,因为摇杆模块本质上就是电位器(模拟输入)和按键(数字输入)的组合,你可以直接使用 Arduino 自带的基础函数来读取摇杆数据。
// 定义摇杆引脚
const int xPin = A0;
const int yPin = A1;
const int buttonPin = 2;void setup() {// 初始化串口通信Serial.begin(9600);// 将按键引脚设置为输入模式pinMode(buttonPin, INPUT_PULLUP);
}void loop() {// 读取X轴和Y轴的模拟值int xValue = analogRead(xPin);int yValue = analogRead(yPin);// 读取按键状态int buttonState = digitalRead(buttonPin);// 输出读取到的值Serial.print("X: ");Serial.print(xValue);Serial.print(" Y: ");Serial.print(yValue);Serial.print(" Button: ");Serial.println(buttonState);delay(100);
}
电位器
电位器,滑动变阻器,旋转旋钮改变输出阻值,故可以直接串联、并联进电路,改变电路阻值。
通过模拟电路调节LED亮度
const int potentiometerPin = A0;
const int ledPin = 3;int sensorValue = 0;
int outputValue = 0; void setup() {Serial.begin(9600);pinMode(ledPin, OUTPUT);
}void loop() {sensorValue = analogRead(potentiometerPin);outputValue = map(sensorValue, 0, 1023, 0, 255); Serial.print("电位器值 = ");Serial.print(sensorValue);Serial.print("\t LED输出 = ");Serial.println(outputValue);analogWrite(ledPin, outputValue); delay(10);
}