Go Down

Topic: Fading LED on pin 13 without delay. (Read 1 time) previous topic - next topic

Haiji

I'm having trouble writing modifying this code that fades the LED on pin 13 on and off to do the exact same thing but without using any delays.

Here is the code which I currently have.

Code: [Select]
int ledPin = 13;
unsigned int i=0;
boolean fade=true;
int interval=1000;
void setup(){
  pinMode(ledPin, OUTPUT);
}
void loop()
{
  if(i == interval)  {
    i=1;
    fade=!fade;
  }
  if(fade == false)  {
    digitalWrite(13, LOW);
    delayMicroseconds(i);
    digitalWrite(13, HIGH);
    delayMicroseconds(interval-i);
  }
  if(fade == true)  {
    digitalWrite(13, LOW);
    delayMicroseconds(interval-i);
    digitalWrite(13, HIGH);
    delayMicroseconds(i);
  }
  i+=1;
}


So far, I converted some of the code but I don't know how to make the Arduino wait without interrupting other code I plan to have running simultaneously.

Can please give me some ideas?

Code: [Select]
int ledState = LOW;
long previous = 0;
long interval = 0;
boolean fade = true;

void setup() {
  pinMode(13, OUTPUT);     
}

void loop()
{
  unsigned long current = micros();
  if(current - previous > interval) {
    previous = current;
    fade = !fade;  //change fading
  }
  //fade out
  if(fade == false)  {
    digitalWrite(13, LOW);
    digitalWrite(13, HIGH);
  }
  //fade in
  if(fade == true)  {
    digitalWrite(13, LOW);
    digitalWrite(13, HIGH);
  }
}
Sie sind das Essen und wir sind die J├Ąger.

Nick Gammon

http://www.gammon.com.au/blink

Use millis ().
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

fungus

No, I don't answer questions sent in private messages (but I do accept thank-you notes...)

Henry_Best


I'm having trouble writing modifying this code that fades the LED on pin 13 on and off to do the exact same thing but without using any delays.

It would be much easier if you connected your LED on one of the PWM pins to control the fading.

CrossRoads

Easier with PWM, but certainly not required. I just wrote some code to output 13 notes from 13 button presses, with frequencies from 261 Hz to 523 Hz. Was certainly not hard using blink without delay type coding.

All you're doing is controlling the on/off time. Setup a time within a time - the outer time is how fast you are pulsing, the inner time is how long you leave the output high within the total time for brightness control.


Designing & building electrical circuits for over 25 years. Check out the ATMega1284P based Bobuino and other '328P & '1284P creations & offerings at  www.crossroadsfencing.com/BobuinoRev17.
Arduino for Teens available at Amazon.com.

Nick Gammon

Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

Go Up