// include the Arduino SPI library
#include <SPI.h>
// define the pins used for the rotary encoder
#define ROTARY_ENCODER_CLK 3
#define ROTARY_ENCODER_DT 4
#define ROTARY_ENCODER_SW 5
// define the pins used for the joystick
#define JOYSTICK_X A0
#define JOYSTICK_Y A1
#define JOYSTICK_SW 2
// variables to store the previous and current state of the rotary encoder
int previousState = 0;
int currentState = 0;
void setup() {
// initialize the serial communication
Serial.begin(9600);
// set the rotary encoder pins as inputs
pinMode(ROTARY_ENCODER_CLK, INPUT_PULLUP);
pinMode(ROTARY_ENCODER_DT, INPUT_PULLUP);
pinMode(ROTARY_ENCODER_SW, INPUT_PULLUP);
// set the joystick pins as inputs
pinMode(JOYSTICK_X, INPUT);
pinMode(JOYSTICK_Y, INPUT);
pinMode(JOYSTICK_SW, INPUT_PULLUP);
}
void loop() {
// read the state of the rotary encoder
currentState = digitalRead(ROTARY_ENCODER_CLK);
if (currentState != previousState) {
if (digitalRead(ROTARY_ENCODER_DT) != currentState) {
// the rotary encoder is rotating clockwise
Serial.println("Clockwise");
} else {
// the rotary encoder is rotating counterclockwise
Serial.println("Counterclockwise");
}
previousState = currentState;
}
// read the state of the joystick
int joystickX = analogRead(JOYSTICK_X);
int joystickY = analogRead(JOYSTICK_Y);
if (joystickX < 100) {
// the joystick is moved to the left
Serial.println("Left");
} else if (joystickX > 900) {
// the joystick is moved to the right
Serial.println("Right");
}
if (joystickY < 100) {
// the joystick is moved upward
Serial.println("Up");
} else if (joystickY > 900) {
// the joystick is moved downward
Serial.println("Down");
}
// read the state of the joystick button
if (digitalRead(JOYSTICK_SW) == LOW) {
// the joystick button is pressed
Serial.println("Joystick Button Pressed");
}
// read the state of the rotary encoder button
if (digitalRead(ROTARY_ENCODER_SW) == LOW) {
// the rotary encoder button is pressed
Serial.println("Rotary Encoder Button Pressed");
}
}