I'm using a rotary encoder on my Arduino Micro, that is supposed to do single steps or ten steps at once, depending on which position a switch is in.
The Rotary: https://www.reichelt.de/drehimpulsegeber-15-impulse-30-rastungen-vertikal-ec11mvbfx-p315144.html?&nbc=1 (on this site are pictures and datasheets as well.)
The Switch: https://www.reichelt.de/miniatur-kippschalter-ein-aus-ein-3-a-250-v-goobay-10023-p285990.html?&nbc=1
Wiring: (image following later)
1--------Pin16 | Pin A3----Switch Rotary 2--------GND | GND-------| 3--------PIN17 |
The rotary encoder gives no output, neither the Serial.print nor the gamecontroller. Also there is no output in either switch position.
EDIT: After using arrays and loops like @jsotola teached me, it works nearly the way its supposed to, but sometimes, although the switch is off, it clicks ten times. The code looks like this shortened now
#include <Arduino.h>
#include <Joystick.h>
#include <BasicEncoder.h>
#include <TimerOne.h>
int EncoderPins[] = {
4, 5, 6, 7, 8, 9, 10, 11
};
int EncoderCount = 8;
BasicEncoder encoder4(EncoderPins[6], EncoderPins[7], HIGH, 2);
void timer_service() {
encoder4.service();
}
#define joyButton16 EncoderPins[6] // Rotary4
#define joyButton17 EncoderPins[7] // Rotary4
#define joyButton18 21 // HDG_SWITCH := Switch to select between single and 10 steps
//Joystick(Joystick HID ID, Joystick Type, Button Count, Hat Switch Count, Include X, Include Y, Include Z, Include Rx, Include Ry, Include Rz, Include Rudder, Include Throttle, Include Accelerator, Include Brake, Include Steering)
Joystick_ Joystick(0x15, JOYSTICK_TYPE_JOYSTICK, 19, 0,
true /*X*/, false/*Y*/, false/*X*/,
false/*Rx*/, false/*Ry*/, false/*Rz*/,
false/*Rudder*/, false/*Throttle*/, false/*Acc*/,
false/*Brake*/, false/*Steer*/);
const bool initAutoSendState = true; // code is sends continuously and doesnt wait for polling
int EncoderState[] = {
0, 0, 0, 0
};
void setup() {
for (int q = 0; q < EncoderCount; q++)
{
pinMode(EncoderPins[q], INPUT_PULLUP);
}
Serial.begin(9600);
Joystick.begin();
Timer1.initialize(100);
Timer1.attachInterrupt(timer_service);
}
void loop() {
GET_CHANGE();
int CurrentButton18State = !digitalRead(joyButton18);
switch(CurrentButton18State){
case 0:
switch(EncoderState[3]){
case 1: clickButton(15); Serial.println(EncoderState[3]); break;
case -1: clickButton(16); Serial.println(EncoderState[3]); break;
} break;
case 1:
switch(EncoderState[3]){
case 1: clickTen(15); break;
case -1: clickTen(16); break;
} break;
}
}
void clickButton(int pin) {
Joystick.setButton(pin, 1);
delay(2);
Joystick.setButton(pin, 0);
}
void clickTen(int pin) {
for (int ii = 0; ii < 10; ii++)
{
clickButton(pin);
Serial.println("step: "); Serial.println(ii);
delay(10);
}
}
void GET_CHANGE()
{
for(int E = 0; E<4; E++)
switch(E) {
case 3: EncoderState[E] = encoder4.get_change(); break;
}
}