const int encoderPinA = 2; // Encoder pin A
const int encoderPinB = 3; // Encoder pin B
const int switchPin = 6; // Sliding switch pin
const int outputPin1 = 10; // Output pin for t > 0 (encoder control)
const int outputPin2 = 11; // Output pin for t <= 0 (encoder control)
volatile int t = 0; // Variable to store the encoder value
volatile int lastEncoded = 0; // Last encoded value
void setup() {
pinMode(switchPin, INPUT_PULLUP); // Initialize the sliding switch pin as an input
pinMode(encoderPinA, INPUT_PULLUP);
pinMode(encoderPinB, INPUT_PULLUP);
pinMode(outputPin1, OUTPUT);
pinMode(outputPin2, OUTPUT);
// Attach interrupts
attachInterrupt(digitalPinToInterrupt(encoderPinA), updateEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(encoderPinB), updateEncoder, CHANGE);
Serial.begin(9600); // Initialize serial communication
}
void loop() {
if (digitalRead(switchPin) == LOW) { // Check if the sliding switch is in the LOW position
Serial.println("Switch is ON. Running encoder function.");
// Display the value of t in the Serial Monitor
Serial.print("Encoder Value: ");
Serial.println(t);
// Use t to control the output pins
if (t > 0) {
digitalWrite(outputPin1, HIGH);
delay(t * 1000);
digitalWrite(outputPin1, LOW);
} else if (t < 0) {
digitalWrite(outputPin2, HIGH);
delay(abs(t) * 1000);
digitalWrite(outputPin2, LOW);
}
// Reset t to 0 after using it
t = 0;
// Delay for a short period to avoid flooding the Serial Monitor
delay(100);
} else {
Serial.println("Switch is OFF. Running analog function.");
float in = (float(analogRead(A1)));
float res = (float(analogRead(A2))) - in;
Serial.println(res);
if (res > 20) {
digitalWrite(outputPin1, HIGH);
digitalWrite(outputPin2, LOW);
} else if (res < -20) {
digitalWrite(outputPin2, HIGH);
digitalWrite(outputPin1, LOW);
} else {
digitalWrite(outputPin1, LOW);
digitalWrite(outputPin2, LOW);
}
delay(100); // Short delay for debouncing and loop pacing
}
}
void updateEncoder() {
int MSB = digitalRead(encoderPinA); // Read the current state of pin A
int LSB = digitalRead(encoderPinB); // Read the current state of pin B
int encoded = (MSB << 1) | LSB; // Combine the two pin states
int sum = (lastEncoded << 2) | encoded; // Create a 4-bit value
if (sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) {
t++; // Clockwise rotation
}
if (sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) {
t--; // Counterclockwise rotation
}
lastEncoded = encoded; // Store the current encoded value
}