I have been trying many variations of code like this, cannot seem to get this to work with how I logically would think it would work. Am I missing something with syntax or breaking some rules? Everything works independently but not jointly.
int switchS = 0;
int var = 1;
void setup() {
pinMode(1,INPUT);
pinMode(7,OUTPUT);
digitalWrite(7,LOW);
}
void loop() {
switchS = digitalRead(1);
while(var == 1)
{
digitalWrite(7,HIGH);
delay(100);
digitalWrite(7,LOW);
delay(100);
if(switchS == HIGH)
{
var = 0;
}
}
delay(5000);
var = 1;
}
-
1I wrote an answer to what I think you are asking, but please be more specific in your question. "work with how I logically would think it would work" We cannot see in your head, so we don't know, what you are thinking how it should work. In every "does not work" question, you should clearly state, what you expected the code to do and what it actually does. That way we can provide way better answers.chrisl– chrisl2019年12月20日 20:40:52 +00:00Commented Dec 20, 2019 at 20:40
1 Answer 1
I guess you want the while loop to exit, when the switch goes to HIGH. (You didn't explain this in your question)
Currently the variable switchS
cannot ever change while the code is in the while loop. The variable var
only changes, when switchS
is HIGH. So, if switchS
is LOW at the start of the while loop, you have an infinite loop.
Instead, you can actually read the switch state inside the while loop, not outside of it. The variable switchS
will not automatically track the state of the switch. You have to explicitly read it. Like this variant of your code:
int switchS = 0;
int var = 1;
void setup() {
pinMode(1,INPUT);
pinMode(7,OUTPUT);
digitalWrite(7,LOW);
}
void loop() {
while(var == 1)
{
digitalWrite(7,HIGH);
delay(100);
digitalWrite(7,LOW);
delay(100);
switchS = digitalRead(1); // I moved this line in the while loop, to read the switch on every loop iteration
if(switchS == HIGH)
{
var = 0;
}
}
delay(5000);
var = 1;
}
Note: You are using pin 1 as input pin. On the Uno this is a Serial (UART) pin, which is used to communicate with the PC. If you have enough pins, that are free, you should not use pins 0 and 1, so that you don't block the serial communication, unless you really need it and know, what you are doing.
-
Yes that is what I was trying to do, I was just about to clarify but you already you answered. Thank you so much, can't believe I missed that.eatsmypasta– eatsmypasta2019年12月20日 20:48:54 +00:00Commented Dec 20, 2019 at 20:48
-
@eatsmypasta Please mark the answer.the busybee– the busybee2019年12月21日 08:12:12 +00:00Commented Dec 21, 2019 at 8:12