Arduino community. I have had experience with Arduino for 3 years now and have finally come to the conclusion to get rid of the delay function entirely.
Below is the code to blink two LEDs a complete 10 times. The problem is that the setup() doesn't repeat like a loop(), which means it doesn't last a long enough to find a time difference between PreviousMillis and CurrentMillis because it runs once; thus, defeating the idea of blinking a LED in the setup(). But, I have researched ways to imitate the loop() with while loops; I have used Adafruit's method to spice things up(Constructors and classes!), https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview.
But I need a little help because it doesn't work, instead, it blinks forever(Mission half-complete =)).
Notice how I have used while loops in the Update(), which is located within the Flasher Class, to mimic a loop() until the condition becomes true.
The problem is, I don't know why this code doesn't work and what to do from here.
The ultimate goal is to blink the LEDs at pin 12 and pin 13 a total of 10 Times, instead of repeatedly blinking for an eternity. I am using an Arduino Uno R3 and a Serial baud rate of 115200.
Ignore what I did in the loop(). It's the same function as the setup() code, instead, the led blinks an eternity (unfortunately), when a value of "1" is typed.
class Flasher{
// Class Member Variables
// These are initialized at startup
int ledPin; // the number of the LED pin
long OnTime; // milliseconds of on-time
long OffTime; // milliseconds of off-time
// These maintain the current state
int ledState; // ledState used to set the LED
unsigned long previousMillis; // will store last time LED was updated
unsigned long currentMillis = 0;
public: Flasher (int pin, long on, long off)
{ // Constructor - creates a Flasher
// and initializes the member variables and state
ledPin = pin;
pinMode(ledPin, OUTPUT);
OnTime = on;
OffTime = off;
ledState = LOW;
previousMillis = 0;
}
void Update(int a){
// check to see if it's time to change the state of the LED
for (int i = 0; i < a; i++) {
while ((currentMillis - previousMillis <= OnTime) || ((currentMillis - previousMillis <= OffTime))) {
currentMillis = millis();
if ((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
{
ledState = LOW; // Turn it off
previousMillis = currentMillis; // Remember the time
digitalWrite(ledPin, ledState); // Update the actual LED
}
else if ((ledState == LOW) && (currentMillis - previousMillis >=OffTime))
{
ledState = HIGH; // turn it on
previousMillis = currentMillis; // Remember the time
digitalWrite(ledPin, ledState); // Update the actual LED
}
}
}
}
};
Flasher led1(12, 100, 400);
Flasher led2(13, 350, 350);
void setup(){
Serial.begin(115200);
led1.Update(10);
}
void loop(){
/* if (Serial.available()) {
String str = Serial.readString();
if (str.substring(0, 1).equals("1")) {
led1.Update(10);
}
}*/
}