i am on a project where i am using increment encoder for angle detection and switching on and off of my components with arduino as per encoder value .my conditions are
1.program should start accepting the encoder input after the signal from D4 to which i have connected IR sensor output when program is started (this is working properly)
2.the pin D13,12 must go high and low as per the values of encoder (this is also working properly)
3.the pin d4 will become high one time for each revolution of my driven component .so from second time of high of D4 pin my encoder value should become zero and star from ZERO (this is to be added)
that is intially the encoder input should be accepted by the program after getting a high pulse from D4 .untill it will not accept encoder input .And for the following pulses from D4 the value of encoder must be reseted to zero .
my code:
int encoderPin1 = 2;
int encoderPin2 = 3;
volatile int lastEncoded = 0;
volatile long encoderValue = 0;
long lastencoderValue = 0;
int lastMSB = 0;
int lastLSB = 0;
int led1 = 13;
int led2=12;
int ir_on = 4;
int on;
int a;
void setup() {
Serial.begin (9600);
pinMode(ir_on,INPUT);
pinMode(encoderPin1, INPUT);
pinMode(encoderPin2, INPUT);
digitalWrite(encoderPin1, HIGH); //turn pullup resistor on
digitalWrite(encoderPin2, HIGH); //turn pullup resistor on
//call updateEncoder() when any high/low changed seen
//on interrupt 0 (pin 2), or interrupt 1 (pin 3)
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
}
void loop(){
//Do stuff here
on=digitalRead(ir_on);
if (on == LOW)
{
a=1;
encoderValue == 0;
}
if(a==1)
{
attachInterrupt(0, updateEncoder, CHANGE);
attachInterrupt(1, updateEncoder, CHANGE);
}
Serial.println(encoderValue);
//delay(1000); //just here to slow down the output, and show it will work even during a delay
}
void updateEncoder(){
int MSB = digitalRead(encoderPin1); //MSB = most significant bit
int LSB = digitalRead(encoderPin2); //LSB = least significant bit
int encoded = (MSB << 1) |LSB; //converting the 2 pin value to single number
int sum = (lastEncoded << 2) | encoded; //adding it to the previous encoded value
if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011)
encoderValue ++;
if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000)
encoderValue --;
lastEncoded = encoded;
//store this value for next time
if((encoderValue >= 1 )&&(encoderValue<=685))
{
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);
}
if((encoderValue > 685)&&(encoderValue<= 2052))
{
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
}
if((encoderValue > 2052 )&&(encoderValue<= 4104))
{
digitalWrite(led2, HIGH);
}
if(encoderValue > 4104 )
{
digitalWrite(led2, LOW);
}
}