Hey all,
I'm working on a project that involves rotary encoders; I downloaded the script online and I'm able to read the "clicks count" of the encoders as well as the direction of the count in the form of [CW; CCW].
This is all good but I'm trying to convert the print of the serial monitor to "0s if CCW" and "1s if CW" to make this data usable for my patch in Max/Msp.
Despite being familiar with conditional statements and Max/Msp coding, I am a newbie in the Arduino world. Thus, I can understand what's going on in the script but I can't get the result I want.
// Rotary Encoder Inputs
#define CLK 2
#define DT 3
#define SW 4
int counter = 0;
int currentStateCLK;
int lastStateCLK;
String currentDir ="";
unsigned long lastButtonPress = 0;
void setup() {
// Set encoder pins as inputs
pinMode(CLK,INPUT);
pinMode(DT,INPUT);
pinMode(SW, INPUT_PULLUP);
// Setup Serial Monitor
Serial.begin(9600);
// Read the initial state of CLK
lastStateCLK = digitalRead(CLK);
}
void loop() {
// Read the current state of CLK
currentStateCLK = digitalRead(CLK);
// If last and current state of CLK are different, then pulse occurred
// React to only 1 state change to avoid double count
if (currentStateCLK != lastStateCLK && currentStateCLK == 1){
// If the DT state is different than the CLK state then
// the encoder is rotating CCW so decrement
if (digitalRead(DT) != currentStateCLK) {
counter --;
currentDir ="CCW";
} else {
// Encoder is rotating CW so increment
counter ++;
currentDir ="CW";
}
if (currentDir ="CCW") {
Serial.print(0) ;
}
if (currentDir ="CW") {
Serial.print(1);
}
Serial.print("Direction: ");
Serial.print(currentDir);
Serial.print(" | Counter: ");
Serial.println(counter);
}
// Remember last CLK state
lastStateCLK = currentStateCLK;
// Read the button state
int btnState = digitalRead(SW);
//If we detect LOW signal, button is pressed
if (btnState == LOW) {
//if 50ms have passed since last LOW pulse, it means that the
//button has been pressed, released and pressed again
if (millis() - lastButtonPress > 50) {
Serial.println("Button pressed!");
}
// Remember last button press event
lastButtonPress = millis();
}
// Put in a slight delay to help debounce the reading
delay(1);
}
Here's the script; this is the part I added
if (currentDir ="CCW") {
Serial.print(0) ;
}
if (currentDir ="CW") {
Serial.print(1);
}