I am using an optical encoder which came along with the stepper motor.
When i tried to read the pulse received from the encoder A+ and B+ with pin 2 and 3 in arduino uno i am receiving continuously increasing value or wrong count of rotation even it is idle.
Please post your sketch, using code tags when you do
In my experience the easiest way to tidy up the code and add the code tags is as follows
Start by tidying up your code by using Tools/Auto Format in the IDE to make it easier to read. Then use Edit/Copy for Forum and paste what was copied in a new reply. Code tags will have been added to the code to make it easy to read in the forum thus making it easier to provide help.
Thanks for your reply. I had added the code i had used for testing the encoder input.
Kindly check this code
long count = 0;
unsigned long timep, time, etime;
bool A, B;
byte state, statep;
void AChange() {
A = digitalRead(2);
B = digitalRead(3);
if (A == HIGH && B == HIGH) state = 1;
if (A == HIGH && B == LOW) state = 2;
if (A == LOW && B == LOW) state = 3;
if (A == LOW && B == HIGH) state = 4;
switch (state) {
case 1:
{
if (statep == 2) count--;
else if (statep == 4) count++;
break;
}
case 2:
{
if (statep == 1) count--;
else if (statep == 3) count++;
break;
}
case 3:
{
if (statep == 4) count--;
else if (statep == 2) count++;
break;
}
case 4:
{
if (statep == 1) count--;
else if (statep == 3) count++;
break;
}
}
statep = state;
}
void BChange() {
A = digitalRead(2);
B = digitalRead(3);
if (A == HIGH && B == HIGH) state = 1;
if (A == HIGH && B == LOW) state = 2;
if (A == LOW && B == LOW) state = 3;
if (A == LOW && B == HIGH) state = 4;
switch (state) {
case 1:
{
if (statep == 2) count--;
else if (statep == 4) count++;
break;
}
case 2:
{
if (statep == 1) count--;
else if (statep == 3) count++;
break;
}
case 3:
{
if (statep == 4) count--;
else if (statep == 2) count++;
break;
}
case 4:
{
if (statep == 1) count--;
else if (statep == 3) count++;
break;
}
}
statep = state;
}
void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
pinMode(3, INPUT);
attachInterrupt(digitalPinToInterrupt(2), AChange, CHANGE);
attachInterrupt(digitalPinToInterrupt(3), BChange, CHANGE);
timep = micros();
A = digitalRead(2);
B = digitalRead(3);
if (A == HIGH && B == HIGH) statep = 1;
if (A == HIGH && B == LOW) statep = 2;
if (A == LOW && B == LOW) statep = 3;
if (A == LOW && B == HIGH) statep = 4;
}
void loop() {
time = micros();
etime = time - timep;
Serial.println(count);
if (etime > 1000000) {
Serial.println(count);
timep = time;
}
}
If you use INPUT_PULLUP then, not surprisingly, the input will be normally HIGH
You need to arrange the circuit so that the input pin is taken LOW when the switch is activated and change the code so that the LOW input is detected rather than the HIGH input
Try the Encoder library from the IDE library manager. Load the "Basic" program from the "Examples" folder and turn the motor by hand to test your encoder.