-1

Why doesn't the code below work? Timer will count 370ms then function called to ON LED. Again 370ms then function called to OFF LED. Basically a toggle function.

int IN0 = 12;
int IN1 = 11;
int OUT1 = 10;
int OUT2 = 9;
int OUT3 = 7;
int OUT4 = 6;
int LED = 13;
unsigned int count = 370;
unsigned int tcount = 0;
bool tflag = 0, mflag = 0, sflag = 0, lflag = 0, rflag = 0;
int a, b;

void setup() {
  pinMode(IN0, INPUT);
  pinMode(IN1, INPUT);
  pinMode(LED, OUTPUT);
  pinMode(OUT1, OUTPUT);
  pinMode(OUT2, OUTPUT);
  pinMode(OUT3, OUTPUT);
  pinMode(OUT4, OUTPUT);
  Timer1.initialize(a); // 370 miliseconds on time
  //Timer1.attachInterrupt(flash);
}

void flash_on() {
  //digitalWrite(LED, !digitalRead(LED));
  digitalWrite(LED, HIGH);
}

void flash_off() {
  //digitalWrite(LED, !digitalRead(LED));
  digitalWrite(LED, LOW);
}

void loop() {
  Timer1.attachInterrupt(flash_on);
  a = count;
  Timer1.attachInterrupt(flash_off);
  a = count;
}
1
  • 1
    At what point do you give the timer the new value you have put in a? Never.
    – Majenko
    Commented Apr 5, 2020 at 14:08

1 Answer 1

1

You should give a a value before calling Timer1.initialize(a).

For example, like this:

void setup() {
  ....
  a = count;
  Timer1.initialize(a); // 370 miliseconds on time
  ....
}

Your loop() code will also not work like you expect it to. As it is, you will be switching between two different ISRs very fast, without having any control over which of the two will be called once the Timer1 interrupt occurs.

It will be better to stick to one ISR that toggles the LED. That’s kind of the point of a Timer interrupt.

1
  • Here, in loop() i've called flash_on() the reason is i've to check the other parameter by polling. Just by toggling in my opinion i cannot do that. If there is any way to do with toggling, request you to please guide me with same.
    – Fatpanda
    Commented Apr 6, 2020 at 5:48

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.