Hello,
I'm working on a project for educational purposes, where I can control the speed of a DC fan (Wathai 12V brushless DC fan) using PWM and a Rotary Encoder (Taiss/AB 2 phase Incremental Rotary Encoder). I'm using a TM1637 4 digit LED display to show the value of the rotary encoder while its changing, I've limited the encoder to go only from 0 to 255, and I've mapped it on the TM1637 so it shows values from 0 to 1200. The codes works and I'm able to control the fan with the encoder. When the encoder reaches 255 the fan speed is at its max, which is what I wanted, but I would like to reset the encoder value back to zero ( which would take the fan to its lowest speed) if the encoder has been on 255 after 5 minutes, but I'm not sure where to add the instructions or how to do so.
Help would be greatly appreciated!
#include <Arduino.h>
#include <TM1637Display.h>
#define CLK 8
#define DIO 9
TM1637Display display(CLK, DIO);
// Define rotary encoder pins
#define ENC_A 2
#define ENC_B 3
volatile int counter = 0;
void setup() {
display.setBrightness(7);
// Set encoder pins and attach interrupts
pinMode(ENC_A, INPUT_PULLUP);
pinMode(ENC_B, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(ENC_A), read_encoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(ENC_B), read_encoder, CHANGE);
// Start the serial monitor to show output
Serial.begin(115200);
}
void loop() {
static int lastCounter = 0;
// If count has changed print the new value to serial
if (counter != lastCounter) {
//Serial.println(counter);
lastCounter = counter;
}
int V = map(counter, 0, 255, 0, 1200);
display.showNumberDecEx(V, 0b01000000, false);
analogWrite(11, counter);
}
void read_encoder() {
// Encoder interrupt routine for both pins. Updates counter
// if they are valid and have rotated a full indent
static uint8_t old_AB = 3; // Lookup table index
static int8_t encval = 0; // Encoder value
static const int8_t enc_states[] = { 0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0 }; // Lookup table
old_AB <<= 2; // Remember previous state
if (digitalRead(ENC_A)) old_AB |= 0x02; // Add current state of pin A
if (digitalRead(ENC_B)) old_AB |= 0x01; // Add current state of pin B
encval += enc_states[(old_AB & 0x0f)];
// Update counter if encoder has rotated a full indent, that is at least 4 steps
if (encval > 3) { // Four steps forward
int changevalue = 1;
counter = counter + changevalue; // Update counter
encval = 0;
if (counter >= 255) {
counter = 255;
}
} else if (encval < -3) { // Four steps backward
int changevalue = -1;
counter = counter + changevalue; // Update counter
encval = 0;
if (counter < 0) {
counter = 0;
}
}
}