I need help if this sketch will work?
#include <Encoder.h>
// Initialize the rotary encoder pins
#define ENCODER_PIN_A 2
#define ENCODER_PIN_B 3
#define LAYER_SWITCH_PIN_C 5
#define BUTTON_SWITCH_PIN_D 6
// Initialize the encoder object
Encoder myEncoder(ENCODER_PIN_A, ENCODER_PIN_B);
// Initialize the mouse movement variables
int mouseX = 0;
int mouseY = 0;
int savedMouseX = 0;
int savedMouseY = 0;
// Initialize the timer variables
unsigned long lastRotationTime = 0;
// Initialize the layer variables
int currentLayer = 1;
void setup() {
// Initialize the encoder pins as inputs
pinMode(ENCODER_PIN_A, INPUT);
pinMode(ENCODER_PIN_B, INPUT);
pinMode(LAYER_SWITCH_PIN_C, INPUT_PULLUP);
pinMode(BUTTON_SWITCH_PIN_D, INPUT_PULLUP);
// Initialize serial communication
Serial.begin(9600);
}
void loop() {
// Read the current encoder position
int newPosition = myEncoder.read();
// If the encoder position has changed, update the mouse position
if (newPosition != 0) {
// Calculate the speed of the mouse movement
int speed = map(newPosition, -1000, 1000, 2, 20);
// Move the mouse
mouseX = newPosition * speed;
// Save the current time
lastRotationTime = millis();
// Check the layer switch
if (digitalRead(LAYER_SWITCH_PIN_C) == LOW) {
// Toggle the current layer
currentLayer = (currentLayer + 1) % 4;
}
// Check the button switch
if (digitalRead(BUTTON_SWITCH_PIN_D) == LOW) {
// Toggle the current layer
currentLayer = (currentLayer + 2) % 4;
}
// Switch between layers
switch (currentLayer) {
case 1:
// Click and hold the left mouse button
Mouse.click(MOUSE_LEFT);
// Move the mouse left or right
if (newPosition > 0) {
mouseX++;
} else if (newPosition < 0) {
mouseX--;
}
delay(40);
break;
case 2:
// Click and hold the left mouse button
Mouse.click(MOUSE_LEFT);
// Move the mouse up or down
if (newPosition > 0) {
mouseY++;
} else if (newPosition < 0) {
mouseY--;
}
delay(40);
break;
case 3:
// Save the mouse location
savedMouseX = MouseX;
savedMouseY = MouseY;
// Click and hold the left mouse button
Mouse.click(MOUSE_LEFT);
// Move the mouse left or right
if (newPosition > 0) {
mouseX++;
} else if (newPosition < 0) {
mouseX--;
}
delay(40);
break;
case 4:
// Save the mouse location
savedMouseX = MouseX;
savedMouseY = MouseY;
// Click and hold the left mouse button
Mouse.click(MOUSE_LEFT);
// Move the mouse up or down
if (newPosition > 0) {
mouseY++;
} else if (newPosition < 0) {
mouseY--;
}
delay(40);
break;
}
}
// If there is no mouse movement detected within 0.4 seconds, release the left mouse button
if (millis() - lastRotationTime > 400 && mouseX != 0 && mouseY != 0) {
Mouse.release(MOUSE_LEFT);
mouseX = 0;
mouseY = 0;
}
// If the current layer is 3 or 4, move the mouse back to the saved location
if (currentLayer == 3 || currentLayer == 4) {
Mouse.move(savedMouseX, savedMouseY);
}
}
moderator edit: proper code tags added