I try modify example "BlinkWithoutDelay", but parameter ledState don't change properly
Please tell me, what i do wrong?
PS sorry for my english
const int ledPin3 = 3; // the number of the LED pin
// Variables will change :
int ledState3 = LOW; // ledState used to set the LED
// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis3 = 0; // will store last time LED was updated
// constants won't change :
const long interval3 = 1000; // interval at which to blink (milliseconds)
void setup() {
// set the digital pin as output:
pinMode(ledPin3, OUTPUT);
}
void timeToBlink(unsigned long currentMillis, unsigned long previousMillis, int* ledState, long interval, int ledPin) {
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (*ledState == LOW) {
*ledState = HIGH;
} else {
*ledState = LOW;
}
// set the LED with the ledState of the variable:
digitalWrite(ledPin, *ledState);
}
}
void loop() {
unsigned long currentMillis = millis();
timeToBlink(currentMillis,previousMillis3, &ledState3, 1000,3);
}
Your problem is not the ledState, but the fact that you do not update previousMillis,
but a local copy of that variable, pass a pointer (or reference) to that too.
void timeToBlink(unsigned long currentMillis, unsigned long* previousMillis, int* ledState, unsigned long interval, int ledPin) {
if (currentMillis - *previousMillis >= interval) {
// save the last time you blinked the LED
*previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (*ledState == LOW) {
*ledState = HIGH;
} else {
*ledState = LOW;
}
// set the LED with the ledState of the variable:
digitalWrite(ledPin, *ledState);
}
}
void loop() {
unsigned long currentMillis = millis();
timeToBlink(currentMillis, &previousMillis3, &ledState3, 1000, ledPin3);
}
Whandall:
Your problem is not the ledState, but the fact that you do not update previousMillis,
but a local copy of that variable, pass a pointer (or reference) to that too.
Thank you! i'm even didn't think about it
PaulS:
How does it change?
You could, and in your case SHOULD, use pass-by-reference, instead of a pointer.
Why i should use pass-by-reference? because it more safer or just because it simpler?
ispite:
Why i should use pass-by-reference? because it more safer or just because it simpler?
References or pointers are both methods to pass a variable by reference.
The difference is the implicit dereference of the pointer that makes the reference,
so you can use '.' instead of '->' and there is no arithmetic defined for references like it is for pointers.