Hi there,
i have an issue regarding the usage of millis(); in combination with the MKR1010. My goal is to have a blinking LED depending on some prerequisites as well as some buttons which will start a counter (without using the delay function as i´d like to run multiple functions in parallel) wich should set an output to HIGH and after the counter throws back a 0, to low. I´m using the internal RGB LED of the Arduino for now.
The code i`ve written so far looks like this:
#include <WiFiNINA.h>
#include <utility/wifi_drv.h>
int ledPin = 1;
int BUTTON1_PIN = 0;
int ledState = 0;
unsigned long previousMillis = 0;
const long interval = 500;
unsigned long previousMillisR1 = 0;
const long intervalR1 = 1000;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(BUTTON1_PIN, INPUT_PULLUP);
WiFiDrv::pinMode(25, OUTPUT); // Green
WiFiDrv::pinMode(26, OUTPUT); // Red
WiFiDrv::pinMode(27, OUTPUT); // Blue
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == 0) {
ledState = 10;
} else {
ledState = 0;
}
// set the LED with the ledState of the variable:
WiFiDrv::analogWrite(25, 0);
WiFiDrv::analogWrite(26, ledState);
WiFiDrv::analogWrite(27, 0);
}
int buttonState = digitalRead(BUTTON1_PIN);
if (buttonState == HIGH) {
WiFiDrv::analogWrite(25, 0);
WiFiDrv::analogWrite(26, 0);
WiFiDrv::analogWrite(27, 20);
digitalWrite(ledPin, HIGH);
Serial.println("Button is pressed");
}
if (currentMillis - previousMillisR1 >= intervalR1) {
previousMillisR1 = currentMillis;
digitalWrite(ledPin, LOW);
}
}
In general the code is doing what i´m expecting. The LED is blinking at an stable interval. The "problem" is, that if i trigger the button the ledPin = 1; will stay on sometimes for 1 second, sometimes just for half a second. It doesn´t matter if i increase the counter value. If i put it to 5 seconds it will also happen that it sometimes sets the LED on for approx. 5 seconds and one hit after for just half a second.
The blinking mode however is working as intended. What am I doing wrong?
Thank you in advance.