Really struggling with this, I'm wanting a fast simple Button encoder to act as a mouse scroll wheel and left click, then trying to add 3 more push buttons on the sketch -with functions: right mouse, middle mouse, and another left button.
Am I going about it the right way? or will I need to use interrupts?
// ** Trying to make a mouse encoder scroll wheel with 4 buttons.
#include <Mouse.h>
#include <Encoder.h>
static unsigned encA=2, encB=3, encBTN=4;
//scaling:
static unsigned hFactor=10, vFactor=5, scrollFactor=4;
unsigned h=0, v=255;
Encoder myEnc(encA, encB);
long oldPosition = -999;
const int mouseButtonLeft = 6;
const int mouseButtonRight = 8;
int buttonState = 0;
void setup(){
pinMode(mouseButtonLeft, INPUT);
pinMode(mouseButtonRight, INPUT);
pinMode(encBTN,INPUT);
Serial.begin(9600);
Mouse.begin();
}
int change=0;
int hChange=0;
int vChange=0;
void loop(){
int clickStateLeft = digitalRead(mouseButtonLeft);
int clickStateRight = digitalRead(mouseButtonRight);
if (clickStateLeft == HIGH) {
if (!Mouse.isPressed(MOUSE_LEFT)) {
Mouse.press(MOUSE_LEFT);
Serial.println("mouseButton_Left");
delay(200);
}
}
else {
if (Mouse.isPressed(MOUSE_LEFT)) {
Mouse.release(MOUSE_LEFT);
}
}
if (clickStateRight == HIGH) {
if (!Mouse.isPressed(MOUSE_RIGHT)) {
Mouse.press(MOUSE_RIGHT);
Serial.println("mouseButton_Right");
delay(200);
}
}
else {
if (Mouse.isPressed(MOUSE_RIGHT)) {
Mouse.release(MOUSE_RIGHT);
}
}
unsigned long newPosition = myEnc.read();
if (newPosition != oldPosition)
{
change += newPosition-oldPosition;
oldPosition = newPosition;
}
if(change<-3 || change>3)
if(digitalRead(encBTN)) //VALUE
{
vChange=change*vFactor;
if((signed)v+vChange<0) v=0; //prevent int underflow
else if(v+vChange>255) v=255; //prevent int overflow
else v+=vChange;
}
else //HUE
{
hChange=change*hFactor;
if((signed)h+hChange<0) h=1541; //prevent int underflow
else if(h+hChange>1541) h=0; //prevent int overflow
else h+=hChange;{
Mouse.move(0,0,+change/scrollFactor);
}
Serial.print("pos: ");
Serial.println(newPosition);
Serial.print("change: ");
Serial.println(change);
Serial.print("Scroll: ");
Serial.println(-change/scrollFactor);
Serial.println();
change=0;
}
}