#include <TM1637Display.h>
// --- TM1637 Display Setup ---
#define CLK_PIN 5 // D5 connected to CLK
#define DIO_PIN 6 // D6 connected to DAT
TM1637Display display(CLK_PIN, DIO_PIN);
// --- Rotary Encoder Setup ---
#define ENCODER_CLK 2
#define ENCODER_DT 3
#define ENCODER_SW A0
// --- Rotary Encoder Variables ---
volatile long encoderCount = 0;
volatile long zeroOffset = 0;
// --- Physical/Resolution Constants ---
const long PPR = 3600;
const long SCALE_FACTOR = 10;
const long MAX_DEGREES_X_SCALE = 360 * SCALE_FACTOR;
// --- Interrupt Service Routine (ISR) ---
void readEncoder() {
if (digitalRead(ENCODER_DT) == HIGH) {
encoderCount++;
} else {
encoderCount--;
}
}
void setup() {
Serial.begin(9600);
pinMode(ENCODER_CLK, INPUT_PULLUP);
pinMode(ENCODER_DT, INPUT_PULLUP);
pinMode(ENCODER_SW, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(ENCODER_CLK), readEncoder, RISING);
display.setBrightness(0x0a);
display.clear();
}
void loop() {
// --- 1. Read Button and Zero Function ---
if (digitalRead(ENCODER_SW) == LOW) {
zeroOffset = encoderCount;
delay(200);
}
// --- 2. Calculate Angle (Scaled) ---
long currentCount = encoderCount - zeroOffset;
long angle_scaled = (currentCount * MAX_DEGREES_X_SCALE) / PPR;
long wrapped_angle_scaled = angle_scaled % MAX_DEGREES_X_SCALE;
if (wrapped_angle_scaled < 0) {
wrapped_angle_scaled += MAX_DEGREES_X_SCALE;
}
int displayValue = (int)wrapped_angle_scaled;
// --- 3. Format and Display (XXX.X format) ---
// ***FIX: Using 0b1000 (8) as the decimal point bitmask***
// This should place the decimal point after the third digit.
display.showNumberDecEx(
displayValue,
(0x00), // Trying the next common bitmask (8) for the decimal point
true
//4,
//0
);
// --- Debug Output ---
float angle_float = (float)wrapped_angle_scaled / SCALE_FACTOR;
Serial.print("Count: ");
Serial.print(currentCount);
Serial.print(" | Angle: ");
Serial.println(angle_float, 1);
delay(10);
}