0

The code below is part of a larger project. The intent is to flash an led with a variable on time, reset the on time and accumulate the total "on" time. The on time is changed each time the "on" period has elapsed.

Code below appears to successfully change the "on" time at the end of each "on" time period, but does not accumulate the total time.
I expected ledtime to equal LED_ON on the first pass (for example 1000) and then equal the previous ledtime + LED_ON (for example 1000 + 2538 = 3528) on the second pass etc.

Instead ledtime is always equal to the current LED_ON, so it appears ledtime is always set to zero on each pass, which I don't understand.

I'm new at arduino/C programming and suspect I'm missing something pretty simple/obvious, but have played with this for awhile with no resolution (including moving the ledtime = etc statements to various areas within the blink routine).

long ledtime;


const int LED_PIN = 13;
const int grnled = 11;
unsigned long LED_ON = 800;       //milliseconds
int LED_OFF = 2000;
int redled = 10;
int yellowled = 12;

unsigned long ms;        //time from millis()
unsigned long msLast;
unsigned long mslast2;//last time the LED changed state
boolean ledState;        //current LED state

void setup(void)
{
  pinMode(grnled, OUTPUT);
  pinMode(redled,OUTPUT);
  pinMode(yellowled,OUTPUT);

  Serial.begin(9600);

}

void loop(void)
{
  while(millis()<5000) {
    digitalWrite(redled,HIGH);
    digitalWrite(yellowled,LOW);
  }
  while (millis() >(5000) && millis()< 20000){


    ms = millis();
    blinkLED();
  }
  if (millis() > 20000 && millis() < 30000) {
    digitalWrite(redled,HIGH);
  }
  if (millis() > 30000) {
    digitalWrite(yellowled,HIGH);
    digitalWrite(redled, LOW);
  }

}
void blinkLED(void)
{


  if (ms - msLast > (ledState ? LED_ON : LED_OFF)) {
    digitalWrite(grnled, ledState = !ledState);
    msLast = ms;
    long ledtime = ledtime + LED_ON;   //this does not work
    Serial.println("ledtime = ");
    Serial.println(ledtime);

    if (ms-mslast2> LED_ON) {
      LED_ON = random(500,5000); //this works
      LED_OFF = 2000;
      mslast2 = ms;
      Serial.println("LED_ON = ");
      Serial.println(LED_ON);


    }

  }
}

1 Answer 1

2

I'm not very sure of what you're trying to do, but with the line you commented, you create a local variable ledtime which has the same name of your global one. And because it's local to your function, it gets erased at the end of your function.

So first initialize ledtime at 0 at its declaration, Then try to replace this line by

ledtime += LED_ON;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.