I'd make the empty loop much more obvious visually here:
while(digitalRead(sw1Pin));
Serial.println("Sw1 pressed ");
// is clearer like this:
while(digitalRead(sw1Pin))
{}
Serial.println("Sw1 pressed ");
Its wise to make all the structure and indentation clear and visually consistent in code, you
may have to read it again some day! In this case a semicolon at the end of an if or a while
can cause huge confusion (witness many threads here!), so its best to always avoid doing it.
Contributors to this Thread might like to reflect on the number of times that it has to be explained to newbies NOT to use blocking code such as WHILE, FOR and delay()
Robin2:
Contributors to this Thread might like to reflect on the number of times that it has to be explained to newbies NOT to use blocking code such as WHILE, FOR and delay()
sure but that's not the question being asked
And actually re-reading the ask, it's not an infinite loop that OP wants, it's really pseudo code like
while (button is pressed)
send '1'
ideally we would let the loop spin and thus it would be
// blink LED when switch pressed
void loop()
{
static unsigned long int time = millis();
if(!digitalRead(sw1Pin) && (millis()-time > 500)) {
digitalWrite(LED1, !digitalRead(LED1));
time = millis();
}
}
void loop()
{
static unsigned long int time = millis();
if(!digitalRead(sw1Pin) && (millis()-time > 500)) {
digitalWrite(LED1, !digitalRead(LED1));
time = millis();
}
}
Noooo....
You are setting time to millis() every time around loop, millis()-time will never be greater than 500.
Also, I suggest it is good practice to take this out of loop and put into it's own function instead off cluttering loop up with lots of code, which just gets confusing.