so i follow this exemple to switch led state with a button and i want to use it also to call a function, but that function should loop till the button is pressed again.
void loop() {
// read the state of the switch into a local variable:
int reading = digitalRead(buttonPin);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited
// long enough since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// only toggle the LED if the new button state is HIGH
if (buttonState == HIGH) {
ledState = !ledState;
Serial.print(ledState);
}
}
}
// set the LED:
digitalWrite(ledPin, ledState);
// save the reading. Next time through the loop,
// it'll be the lastButtonState:
lastButtonState = reading;
}
So now when the led State is equal to 1 i want to call a function in loop so read some sensor value and stop ip if the led state change.
what is the right way?
If you just want that function to be called repeatedly, you can take advantage of the fact that loop is being called perpetually and just put this as the last thing in loop:
if (ledstate)
{
Function2();
}
If you use your while loop instead, you will need to make sure that something in function2 is reading the button and adjusting the led state.
You should probably look at debouncing your button too.
i found it i had a delay i forgot to erase in the second function... i will let my code anyways. ( now its working however if i had a delay it dosent work)
if (buttonState == HIGH) {
ledState = !ledState;
Serial.print(ledState);
}
}
}
....
// set the LED:
digitalWrite(ledPin, ledState);
// save the reading. Next time through the loop,
// it'll be the lastButtonState:
lastButtonState = reading;
if(ledState==1){
funcaomw();
}
}
void funcaomw(){
int x,y,z; //triple axis data
int k; //triple axis data
//Tell the HMC5883 where to begin reading data
Wire.beginTransmission(address);
Wire.write(0x03); //select register 3, X MSB register
Wire.endTransmission();
int tempo= 0;
if((tempo=0)|| (tempo=2)){
//Read data from each axis, 2 registers per axis
Wire.requestFrom(address, 6);
if(6<=Wire.available()){
x = Wire.read()<<8; //X msb
x |= Wire.read(); //X lsb
myReadings[0]=x;
x |= Wire.read(); //X lsb
myReadings[1]=x;
x |= Wire.read(); //X lsb
myReadings[2]=x;
x |= Wire.read(); //X lsb
myReadings[3]=x;
}
static int ola = x;
Serial.print("sample:");
Serial.println(ola);
Serial.println(x);
if((x>ola-20) && (x<ola+20) )
{ Serial.println("off");
tempo=2;
}
else
{ Serial.println("on");
}
}