My code compiles and uploads OK.
But the while loop will not exit when the KY40 button is pressed or even if's button switch is constantly pushed. I determined the KY40 button switch IS working. I also grounded pin 4, but the while loop will NOT exit. Also, I'm pretty certain my KY40 bush-button switch has an internal pull-up itself.
Help please! My code follows.
// Rotary Encoder Inputs
int CLK=2;
int DT=3;
int SW=4;
int x;
void setup() {
// Set encoder pins as inputs
pinMode(CLK,INPUT);
pinMode(DT,INPUT);
pinMode(SW,INPUT_PULLUP);
// Setup Serial Monitor
Serial.begin(9600);
}
void loop() {
Serial.println("This is void loop");
delay(1000);
KY40();//call KY40
}
int KY40(){
Serial.println("This is KY40 while loop");
digitalRead (SW);
while(SW=HIGH){
digitalRead (SW);
delay(100);
x=x+1;
Serial.println(x);
delay(250);
}
}
You are correct. ... I forgot the double ==. My corrected sketch is below.
But now, the while loop doesn't execute at all i.e. x never increments. It seems as though the (SW==HIGH) condition always fails and SW is always LOW.
What am I missing ??
// Rotary Encoder Inputs
int CLK=2;
int DT=3;
int SW=4;
int x;
void setup() {
// Set encoder pins as inputs
pinMode(CLK,INPUT);
pinMode(DT,INPUT);
pinMode(SW,INPUT_PULLUP);
// Setup Serial Monitor
Serial.begin(9600); // put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println("This is void loop");
delay(1000);
KY40();//call KY40
}
int KY40(){
Serial.println("This is KY40 while loop");
digitalRead (SW);
while(SW==HIGH){
digitalRead (SW);
delay(1);
x=x+1;
Serial.println(x);
delay(250);
}
}
SW, if it being read, must be a pin, i.e. an integer. digitalRead(SW) is not being assigned to anything. That woud require SW = digitalRead(SW), which would likely change the value of SW, and you'd no longer be reading the pin. If SW in the pin, use something like SWValue - digitalRead(SW)
digitalRead (SW); // read the switch input (pin 4) and throw the result away
while(SW==HIGH){ // if 4 is 1 execute the while block, SW is a pin number
bool swVal = digitalRead (SW); // read pin 4 and assign the state to the variable swVal
while(swVal == HIGH){ // if the switch is not pressed execute the while block
Assuming a switch wired to ground and the internal pullup enabled, if you want to execute the code in the while block when the switch is pressed:
bool swVal = digitalRead (SW); // read pin 4 and assign the state to the variable swVal
while(swVal == LOW){ // if the switch is pressed execute the while block