#include <DigiPotX9Cxxx.h>
const int encoderPinA = 2;
const int encoderPinB = 3;
const int csPin = 4; // Chip-select pin
const int udPin = 5; // UpDown (UD) pin
volatile int encoderValue = 0;
volatile int lastEncoded = 0;
void setup() {
Serial.begin(9600);
pinMode(encoderPinA, INPUT_PULLUP);
pinMode(encoderPinB, INPUT_PULLUP);
pinMode(csPin, OUTPUT);
pinMode(udPin, OUTPUT);
digitalWrite(csPin, HIGH); // Deselect MCP4011 initially
digitalWrite(udPin, LOW); // Set UD to 0 initially
attachInterrupt(digitalPinToInterrupt(encoderPinA), handleEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(encoderPinB), handleEncoder, CHANGE);
}
void loop() {
// Do other tasks here if needed
}
void handleEncoder() {
int MSB = digitalRead(encoderPinA);
int LSB = digitalRead(encoderPinB);
int encoded = (MSB << 1) | LSB;
int sum = (lastEncoded << 2) | encoded;
if (sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) {
// Clockwise rotation
if (encoderValue < 255) {
encoderValue++;
updateMCP4011(encoderValue, true);
}
} else if (sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) {
// Counter-clockwise rotation
if (encoderValue > 0) {
encoderValue--;
updateMCP4011(encoderValue, false);
}
}
lastEncoded = encoded;
}
void updateMCP4011(int value, bool isUp) {
digitalWrite(csPin, LOW); // Select the MCP4011 chip
// Set UD to the desired direction
digitalWrite(udPin, isUp ? HIGH : LOW);
delayMicroseconds(10); // Add delay if necessary
// Toggle UD for the MCP4011 to recognize the change
digitalWrite(udPin, !digitalRead(udPin));
delayMicroseconds(10); // Add delay if necessary
digitalWrite(csPin, HIGH); // Deselect the MCP4011 chip
delayMicroseconds(10); // Add delay if necessary
}