LED either turns on or off after each run

Hello all,

I am a new arduino user. I have a project where I need to blink my LED 8 times in a second. I wrote the following code for this. Although LED blinks succesfully it fails to close at the end of designated time (1 minute) it sometimes stay open or closes (one by one) I could not see the problem on my code so I am asking for help from you. I appreciate any suggestions.

Thank you
Code:

const byte  buttonPin = 7;    // the pin that the pushbutton is attached to
// constants won't change. Used here to set a pin number:
const int ledPin = 8;  // the number of the LED pin
unsigned long keepBlinkingUntil = millis();

boolean ledState = LOW;
boolean previousButtonState = HIGH;
boolean buttonState = LOW;
boolean serialCheck = LOW;

long duration = 0;

unsigned long previousMillis = 0;        

// constants won't change 62.5 is for 8 hz if 4 hz use 125 :
const long interval = 62.5;

void setup()
{
  Serial.begin(9600);
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin,INPUT);
}

void loop()
{
  Serial.print("do not worry i am working");
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval) { 
    previousMillis = currentMillis;   
    if (currentMillis < keepBlinkingUntil){
      if (ledState == LOW) {
        ledState = HIGH;
      }
      else {
        ledState = LOW;
      }

      // set the LED with the ledState of the variable:
      digitalWrite(ledPin, ledState);
    }
    
    if (millis() >= duration && buttonState == HIGH) {
      previousButtonState = buttonState;
      buttonState = LOW;
    }
  }
  
  if(digitalRead(buttonPin) == HIGH) {
    Serial.print("buttonPin suan HIGH");
    if(previousButtonState == HIGH) {
      buttonState = HIGH;
      Serial.print("buttonState HIGH yaptik");
    }
    else {
      buttonState = LOW;
      Serial.print("buttonState LOW yaptik");
    }
    delay(5); //debouncing
    duration = millis() + 60000;
    keepBlinkingUntil = duration;
  }
}

Hi!

Try this:

#include <Arduino.h>
#include <Bounce2.h> // https://github.com/thomasfredericks/Bounce2/archive/refs/heads/master.zip


Bounce2::Button button = Bounce2::Button();

const int buttonPin = 4;
const int ledPin = 10;

const int blinktime = 60; // Seconds
const int blinkPerSecond = 8;
const int blinkPerTime = blinktime * blinkPerSecond;
const int blinkInteval = (blinktime * 1000UL) / blinkPerTime;

unsigned long prevMicros = 0;
unsigned long stepMicros = 0;
unsigned long blinkMillis = 0;

bool startBlink = false;
bool ledState = false;
int countBlink = 0;
int totalBlink = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);

  button.attach(buttonPin, INPUT_PULLUP);
  button.interval(5); // interval im ms
  button.setPressedState(LOW);
}

void loop()
{
  button.update();

  if (button.pressed())
  {
    if (startBlink == false)
    {
      startBlink = true;
      countBlink = 0;
      totalBlink = 0;
      prevMicros = micros();
      blinkMillis = millis();
    }
  }

  if (((micros() - prevMicros) <= (blinktime * 1000UL * 1000UL)) && (startBlink == true))
  {
    if ((micros() - stepMicros) >= ((blinkInteval * 1000UL) / 2))
    {
      ledState = !ledState;
      digitalWrite(ledPin, ledState);

      if(ledState == true)
      {
        countBlink++;
        totalBlink++;
      }
      if((millis() - blinkMillis) >= 1000)
      {
        Serial.print("countBlink: ");
        Serial.print(countBlink);
        Serial.print(", totalBlink: ");
        Serial.println(totalBlink);
        countBlink = 0;
        blinkMillis = millis();
      }
      stepMicros = micros();
    }
  }
  else
  {
    digitalWrite(ledPin, LOW);
    startBlink = false;
  }
}

Is not perfect but it's almost. Removing the serial print and unneeded parts could improve.

Total blink after 1 minute : 475. The right number is 480.

Tested on ESP32. :smiley:

Best regards.

Is it for school ?

8 blinks per second, that is 62.5 milliseconds on and the same time off.
For a minute it should blink 480 times.

There is only one timing thing to do, therefor I see a single millis-timer (or micros-timer) that counts up to 480.

Let's bend the rules, and turn the led on for 62 milliseconds and then off for 63 milliseconds.
This is with a single millis-timer:

// Blink a led 8 times per second for a minute
//
// This sketch bends the rules, by using millis() and 62 and 63 for the blink.
// Blinking 8 times per second would be a interval of 62.5 ms.
//
// The blinking is almost too fast to be visible in Wokwi.
//

const unsigned long onTime = 62;
const unsigned long offTime = 63;

unsigned long previousMillis;
unsigned long interval = offTime;    // start with led off

const int ledPin = 13;
int ledState = LOW;                  // start with low
const int buttonPin = 2;

bool blinkingEnabled = false;        // don't blink to start with.
int count;
const int maxCount = 8 * 60;         // 8 blinks per second, 60 seconds

void setup()
{
  Serial.begin(115200);
  Serial.println( "Press the button to start");

  pinMode( ledPin, OUTPUT);
  pinMode( buttonPin, INPUT_PULLUP);
}

void loop()
{
  unsigned long currentMillis = millis();

  if( digitalRead( buttonPin) == LOW)
  {
    blinkingEnabled = true;
    count = 0;
  }

  if( blinkingEnabled)
  {
    if( currentMillis - previousMillis >= interval)
    {
      previousMillis += interval;     // clock-accurate millis-timer
      
      if( ledState == HIGH) // led was on ?
      {
        interval = offTime;
        ledState = LOW;
        if( count >= maxCount)        // blinked all the blinks ?
        {
          blinkingEnabled = false;    // turn of this millis-timer
        }
      }
      else                  // led was off
      {
        interval = onTime; 
        ledState = HIGH;
        count++;            // count the number the led is turned on
      }
      digitalWrite( LED_BUILTIN, ledState); // set new led state
    }
  }
}

Try the sketch in Wokwi:

hey, tried this exact code but the light is no coming on

hello this did not ran on my end. Do I need to export another file for this to run?

Hello m6363

Check, try and modify this sketch to your needs.

constexpr int NumberOfBlinks {480};
constexpr unsigned long BlinkNoBlink[] {62,63}; 
int numberOfBlinks;

void setup() 
{
  pinMode( LED_BUILTIN , OUTPUT);
  Serial.begin(115200); 
  numberOfBlinks=NumberOfBlinks;
}
void loop() 
{
  static unsigned long blinkNow=millis();
  if(millis()-blinkNow >= BlinkNoBlink[digitalRead(LED_BUILTIN)] && numberOfBlinks)
  {
    blinkNow=millis();
    numberOfBlinks--;
    digitalWrite(LED_BUILTIN,digitalRead(LED_BUILTIN)?LOW:HIGH);
  }
}

Have a nice day and enjoy coding in C++.

What do you mean?

Did you open the Serial Monitor and did you see the message and do you have a button at pin 2 and a led at pin 13 ?

Hi, @m6363
Welcome to the forum.

Now is the time for a schematic of your project.
Can we please have a circuit diagram?
An image of a hand drawn schematic will be fine, include ALL power supplies, component names and pin labels.

Thanks.. Tom.. :smiley: :+1: :coffee: :australia:

Hello yes I did serial monitor gave this. also the led is not following the button with this code
image

What happens with my code?

hey . Thanks for your comment. I installed the libraries and it worked. As you mentioned total number of blink is 475 right now. Is there a way to increase it to 480?

Glad to hear!

Removing the serial print and unneeded parts could improve.

:point_up_2:

BTW if you are going to add more functions to this code I believe it won't be viable because the MCU will loose time with others tasks.

I could recommend you to look for some dedicated circuit like NE555 to generate this signal.

Edit: Maybe using an ESP32 you could use 1 core for this task and another to others tasks.

thank you for the reply, I will not add more functions but I need precise 480 blinks. I removed the serial print but it still gives me 476

I don't know how you will count the pulses but this code will give you the best result.

#include <Arduino.h>
#include <Bounce2.h> // https://github.com/thomasfredericks/Bounce2/archive/refs/heads/master.zip

Bounce2::Button button = Bounce2::Button();

const int buttonPin = 4;
const int ledPin = 10;

const int blinktime = 60; // Seconds
const int blinkPerSecond = 8;
const int blinkPerTime = blinktime * blinkPerSecond;
const int blinkInteval = (blinktime * 1000UL) / blinkPerTime;

unsigned long prevMicros = 0;
unsigned long stepMicros = 0;

bool startBlink = false;
bool ledState = false;

void setup()
{
  pinMode(ledPin, OUTPUT);

  button.attach(buttonPin, INPUT_PULLUP);
  button.interval(5); // interval im ms
  button.setPressedState(LOW);
}

void loop()
{
  if (startBlink == false)
  {
    button.update();

    if (button.pressed())
    {
      startBlink = true;
      prevMicros = micros();
    }
  }

  if (((micros() - prevMicros) <= (blinktime * 1000UL * 1000UL)) && (startBlink == true))
  {
    if ((micros() - stepMicros) >= ((blinkInteval * 1000UL) / 2))
    {
      ledState = !ledState;
      digitalWrite(ledPin, ledState);

      stepMicros = micros();
    }
  }
  else
  {
    digitalWrite(ledPin, LOW);
    startBlink = false;
  }
}

If you change that line to

stepMicros += ((blinkInteval * 1000UL) / 2);

Then it would account for jitter due to printing or other processing that delays the trigger--If something runs long one cycle, it makes up for it in the next cycle.

Hi!

I don't know why OP want high precision but at least on simulator. :smiley:

Best regards.

The below may answer about frequency,

// ************************************
// T  = 1 / F
//    = 1 / 1 Hz
//    = 1 second(S) = 1,000 milliseconds(mS) = 1,000,000 microseconds(uS)
//
// Duty Cycle = 50 % @T= 1 S
//         _______         ____
//        |       |- T/2 -|
//        |  TON  |  TOFF |
//    ____|- T/2 -|_______|
//
// TON  = 500 mS = 500,000 uS
// TOF  = 500 mS = 500,000 uS
//
// *** Time Interval (Ti) For Toggle ***
// Ti   = 0.5 / F
//      = 500,000 uS / F
// #define F2Ti(Frequency) (500,000 uS/Frequency)
//
// ************************************
#define F2Ti(frequency) (500000UL/frequency)

const uint16_t frequency = 8;                     // <- Set your frequency (Hz)
const unsigned long interval = F2Ti(frequency);   // Frequency to Time Interval

For your reference,
NOTE: Not consider button-debounce, interrupt-timer, and PWM output.

Arduino Simulator: Blink.ino

#define ledPin 7
#define startPin A0
#define F2Ti(frequency) (500000UL/frequency)
#define MILLISEC(time) (time * 1000UL)            // Define calculator for time in second

const uint16_t frequency = 8;                     // <- Set your frequency (Hz)
const unsigned long interval = F2Ti(frequency);   // Frequency to Time Interval

const bool firstState = HIGH;       // FIRST state for LED
bool blink = false;                 // Variable for blink state
unsigned long startInterval = 0UL;  // Reset start time
unsigned long count = 0;


const unsigned long duration = MILLISEC(60000);    // <- Set your duration n milliseconds
unsigned long startTime = 0UL;

bool startState = false;      // Start state
bool pressState = false;      // Press state
bool buttonState = false;     // Button state
bool prevButtonState = false; // previous Button state

void InitialRoutine();
void StartStopRoutine();
void TimerRoutine();
void BlinkRoutine();

void setup() {
  Serial.begin(115200);
  pinMode(startPin, INPUT_PULLUP);  // button pin mode
  pinMode(ledPin, OUTPUT);          // LED pin mode
  InitialRoutine();
}

void loop() {
  prevButtonState = buttonState;
  buttonState = digitalRead(startPin);          // Read button state
  pressState = !buttonState & prevButtonState;  // Rising edge detector

  StartStopRoutine();
  TimerRoutine();
  BlinkRoutine();
}

void InitialRoutine() {
  startState = false;         // Stop blink
  digitalWrite(ledPin, LOW);  // Write low state to LED
}

void StartStopRoutine() {
  if (pressState) {
    startState = !startState;     // Invert start state
    if (startState) {
      startInterval = micros();   // Load blink time
      blink = firstState;         // Set blink with default first state
      startTime = startInterval;  // Load start time
      count = 0;                  // Reset counter
      digitalWrite(ledPin, firstState); // Write state to LED
    } else {
      InitialRoutine();
    }
  }
}

void TimerRoutine() {
  if (startState) {
    unsigned long elapsedTime = micros() - startTime;  // Elapsed Time
    if (elapsedTime >= duration) {
      InitialRoutine(); // Stop blink
    }
  }
}

void BlinkRoutine() {
  if (startState) {
    unsigned long currInterval = micros();
    if (currInterval - startInterval >= interval) {
      startInterval = currInterval;
      if (blink) count++;
      blink = !blink;                 // Toggle blink state
      digitalWrite(ledPin, blink);    // Write state to LED
    }
  }
}