Hi everyone, i'm tryng to interface a rotary encoder with a midi device, and this encoder has to change program on board.
I have a 5 pin encoder, with 3 pins in a face, and 2 in the other one. The encoder has a switch too, but in this moment i don't need.
I have connected the two extreme pins (3 pins side) on arduino digital 10 and 11, and the central pin to the ground.
The sketch i'm using is this one i found on sparkfun site (if i remember well!)
/**
- code to read one quadratic rotary encoder gray code.
- rights: Creative Commons — Attribution-ShareAlike 3.0 Unported — CC BY-SA 3.0
*/
int inputPin1 = 10; // A
int inputPin2 = 11; // B
int val1 = 0, val2 = 0;
int oldVal1 = 0, oldVal2 = 0;
int pos = 0, oldPos = 0;
int turn = 0, oldTurn = 0, turnCount=0;
/**
- this is the heartbeat function for the rotary encoder
- should be called from the loop()
*/
void rotEnc () {
val1 = digitalRead(inputPin1);
val2 = digitalRead(inputPin2);
// Detect changes
if ( val1 != oldVal1 || val2 != oldVal2) {
//for each pair there's a position out of four
if ( val1 == 1 && val2 == 1 ) // stationary position
pos = 0;
else if ( val1 == 0 && val2 == 1 )
pos = 1;
else if ( val1 == 0 && val2 == 0 )
pos = 2;
else if ( val1 == 1 && val2 == 0 )
pos = 3;
turn = pos;
if (abs(turn) != 2) // impossible to understand where it's turning otherwise.
if (turn == -1 || turn == 3)
turnCount++;
else if (turn == 1 || turn == -3)
turnCount--;
if (pos == 0){//KP3
if (turnCount<0){(turnCount=127);
}
else if (turnCount>127){(turnCount=0);
}
midiCC(0xC0,0,turnCount);
}
oldVal1 = val1;
oldVal2 = val2;
oldPos = pos;
oldTurn = turn;
delay(20);
}
}
void setup() {
pinMode(inputPin1, INPUT);
digitalWrite(inputPin1, HIGH);
pinMode(inputPin2, INPUT);
digitalWrite(inputPin2, HIGH);
Serial.begin(31250);
}
void loop(){
rotEnc();
}
void midiCC(char command, char value1, char value2){
Serial.print(command, BYTE);
Serial.print(value1, BYTE);
Serial.print(value2, BYTE);
}
The problem is that encoder works fine, but is not too responsive. If i turn left or right is not sure that change the same number of programs in the midi device. Maybe i make 5 steps fast, and the midi change only 2. Or if i turn wheel very fast, maybe in midi device only 1 program change.
I've modified this line:
turn = pos;
because the original one was:
turn = pos-oldPos;
but with this method, every step i made on my encoder change 4 steps in midi device instead of 1.
Can anyone please help me to calibrate my encoder?
It's very important for me, because this is the last part of a bigger project, that has taken 3 months of my life!!!
Thanks for every help.