I use an Arduino Leonardo and a 10k linear potentiometer. The potentiometer has a rotation range of 270 degrees, of which only 110 degrees are used by mechanical stops. Now the 100 degree rotation range is converted. The current position of the pot is set as 50%. so that a driving brake lever for train simulators works. that works up to here too. Only in the range of 50-100% does the value increase too quickly.
#include <Joystick.h>
// Joystick-Objekt initialisieren
Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID, JOYSTICK_TYPE_JOYSTICK,
0, 0, // Keine Buttons, keine Achsen außer X
true, false, false, // X-Achse aktiv, Y und Z deaktiviert
false, false, false, // Keine Rotation
false, false, // Keine rudder/throttle/accelerator
false, false, false); // Keine Hat Switches
const int potentiometerPin = A0; // Potentiometer-Pin
const int smoothingFactor = 10; // Für Glättung (höher = mehr Glättung)
int rawValue = 0; // Rohwert vom Potentiometer
float smoothedValue = 0; // Geglätteter Wert
float zeroPoint = 0; // Dynamisch kalibrierter Nullpunkt
const int potentiometerMin = 0; // Minimaler Wert vom Potentiometer
const int potentiometerMax = 1023; // Maximaler Wert vom Potentiometer
void setup() {
pinMode(potentiometerPin, INPUT);
calibrateToCurrentPosition();
Joystick.begin();
Joystick.setXAxisRange(-100, 100);
}
void loop() {
rawValue = analogRead(potentiometerPin);
smoothedValue += (rawValue - smoothedValue) / smoothingFactor;
// Kalibrierte Werte für X-Achse berechnen
int calibratedValue = map(smoothedValue, potentiometerMin, potentiometerMax, -100, 100);
// Langsame Reaktion im Bereich von -100 bis +30
if (calibratedValue <= 30) {
calibratedValue = map(calibratedValue, 100, -30, 100, -30); // Langsame Skalierung
}
calibratedValue = constrain(calibratedValue, -100, 100);
// Werte in den Joystick schreiben
Joystick.setXAxis(calibratedValue);
delay(10);
}
void calibrateToCurrentPosition() {
int currentValue = analogRead(potentiometerPin);
zeroPoint = currentValue;
}