Hello.
I have spent hours and hours trying to accomplish my goal but I fail miserably.
I have bought one of those encoders which contain RGB diodes and a switch from sparkfun:
I had thought to write a class for this but first I need to make a sketch do what I want it to do, enabling single-, double-click and click-and_hold.
I am using an external interrupt to detect when the switch activates and I need to do something like:
void switchAction()
{
if(this is the second click | withing 600mS since the first click)
{
doubleClick();
}
if(this is the first click)
{
if(hold time is les than 1000mS)
{
singleClick();
}
else if(hold time is more than 1000mS)
{
clickAndHold();
}
}
}
I don't like using volatile variables declare outside switchAction() but I find that I need to use several, though all my attempts at this has failed so far. I've tried using a clickCount variable but no success and I could really need some help.
I'll attach what I have that is working though it is not complete.
Regards
tryenc.ino (2.04 KB)
This is my lasted try on a code/pseudo-code:
void switchAction()
{
unsigned long T = micros;
static unsigned long oldT = 0;
static uint8_t clickCount;
unsigned long secInterval = oldT - T;
if(clickCount > 0 | secIntervsl < 60000)
{
doubleClick();
clickCount = 0;
}
else if(clickCount != 1 | )
{
if (T - oldT < 100000)
{
}
else
{
if(hold time is les than 1000mS)
{
singleClick();
clickCount = 1;
}
else if(hold time is more than 1000mS)
{
clickAndHold();
}
}
oldT = T;
}
Use timers and interrupts.
Code starting with "%" indicates raw pseudocode
Pseudocode:
#define clickPin 10
volatile int flag = 0;
attachInterrupt(clickPin, beginAction, RISING);
attachInterrupt(clickPin, clickAction, FALLING);
void beginAction()
{
if(flag==2 && timer1<timerD_threshold) //this means the signal went low once and doubleclick timer hasn't timedout, hence doubleclick happed.
{
doubleClick();
}
% start a timer timer1 //for click vs hold
%start a timer timer2 //for click vs double click
%set timer1 reset threshold //timer1 clears after this time is reached. Anything after this time is declared a "hold"
%set timer2 reset threshold //if timer2 is
%make sure to take care of timer overflows
flag = 1;
}
void clickAction() //happens when signal goes low
{
if (flag == 1 && timer1>holdThreshold) //if a LOW occurs after a threshold, it's a hold
{
hold();
%reset timer1
}
flag++;
}
void doubleClick()
{
//blah blah
flag = 0;
}
void singleClick()
{
//blah blah
flag = 0;
}
void hold()
{
//blah blah
flag = 0;
}
you get the point