0

I'm trying to get an LED fading in and out while other code is running, as a nice status indicator. I've asked here how to do this, and I got the suggestion to use the msTimer2 library. This seemed to work, until I tried to use analogWrite in the code. It just skips that part. When I remove the library it works again, but of course then I don't have the status indicator working. Why won't my code work?

int ledPin = 10;
int brightness = 0;
int fadeAmount = 1;
#include <MsTimer2.h>

void flash() {
  for(int fadeValue = 20 ; fadeValue <= 21; fadeValue +=1) {   
    delay(20000);                            
  }

    for(int fadeValue = 20 ; fadeValue <= 220; fadeValue +=1) {
    analogWrite(ledPin, fadeValue);          
        delay(50);                            
  }

  for(int fadeValue = 220 ; fadeValue >= 50; fadeValue -=1) {
    analogWrite(ledPin, fadeValue);           
    delay(50);
  }

    for(int fadeValue = 50 ; fadeValue <= 110; fadeValue +=1) {
    analogWrite(ledPin, fadeValue);          
    delay(130);                            
  }

  for(int fadeValue = 110 ; fadeValue >= 20; fadeValue -=1) {
    analogWrite(ledPin, fadeValue);          
    delay(250);
  }



}

void setup() {
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(11, OUTPUT);

  MsTimer2::set(500, flash); 
  MsTimer2::start();
}

void loop() {
  digitalWrite(9, 1);
  delay(1000);
  digitalWrite(11, 1);
  delay(1000);
  digitalWrite(9, 0);
  delay(1000);
  digitalWrite(11, 0);
  delay(1000);
  analogWrite(9, brightness);    
  brightness = brightness + fadeAmount;
  delay(400);   
}
kajdehoop
  • 517
  • 8
  • 22
  • analogwrite is a PWM, using timer2 so you have a conflict of resources. – mpflaga Mar 03 '13 at 21:27
  • Thanks! After reading some more about PWM I already guessed it had to be something like that. Do you know of any solution to run both bits of code at the same time, or is this simply not possible? – kajdehoop Mar 05 '13 at 19:17
  • Did you try using pins 5 and 6 instead of 9 and 11? Pins 9 and 10 utilize the same timer/counter (Timer/counter 1), which may be the source of the issue. Pins 5 and 6 use timer/counter 0 (I looked this up from Dale Wheat's book "Arduino Internals"). – mbaytas Mar 06 '13 at 09:51

0 Answers0