Hello, I hope this is the correct place to post this. Couldn't find anywhere that involved the coding of random parts.
Alright so, I'm trying to use a rotary encoder from spark fun. Its pretty straightforward, two outputs (A and B) and a SW output.
//these pins can not be changed 2/3 are special pins
int encoderPin1 = 4;
int encoderPin2 = 3;
int encoderSwitch = 7;
volatile int lastEncoded = 0;
volatile long encoderValue = 0;
long lastencoderValue = 0;
int lastMSB = 0;
int lastLSB = 0;
void setup() {
Serial.begin (9600);
pinMode(encoderPin1, INPUT);
pinMode(encoderPin2, INPUT);
digitalWrite(encoderPin1, HIGH); //turn pullup resistor on
digitalWrite(encoderPin2, HIGH); //turn pullup resistor on
digitalWrite(encoderSwitch,HIGH);
//call updateEncoder() when any high/low changed seen
//on interrupt 0 (pin 2), or interrupt 1 (pin 3)
attachInterrupt(0, updateEncoder, CHANGE);
attachInterrupt(1, updateEncoder, CHANGE);
}
void loop(){
if(encoderSwitch > 0)
{
analogWrite(A0, 255);
}
while(encoderValue == lastencoderValue)
{
analogWrite(A3, 255);
analogWrite(A4, 0);
analogWrite(A2,0);
}
if (encoderValue > lastencoderValue)
{
analogWrite(A4, 255);
analogWrite(A2, 0);
}
if (encoderValue < lastencoderValue)
{
analogWrite(A2, 255);
analogWrite(A4, 0);
}
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
}
I'm trying to verify that my code works with 4 LED's. I have a base LED that lights up when the lastencodervalue is equal to the encoded value, and an Up and Down LED for when the encoder is turned CW or CCW. I also have a switch LED for when the pushbutton is pressed.
Here is my problem(s)
As stated before, I want my LED's to light when they're increasing or decreasing. A problem I'm having is that the LED will light when turned CW (causing the encoded value to go up, viewable via serial monitor), but when I turn the encoder CCW, the up LED only turns off when the count coming out of the A and B get below Zero. (Viewable via serial monitor)
Another problem is the switch. I thought that when the switch is pressed that it would send a high pulse in, so I tried to make a statement that was along the lines of
if (encoderSwitch == HIGH)
{
analogWrite(A0, 255) //supplies 5V to the LED on pin A0 when Pin is pressed
}
But this doesn't yield any results.
Help?
Thank you!