Hi,
I am controlling some leds by PWM through a transistor and that works fine.
I have two led modes and pushing a button switches between the two modes.
One mode however uses a delay and I want to re make the function without the delay by using millis().
Here is my full code.
/*
PWN Led's with a transistor.
A transistor is needed because more than 2 LEDs draw too much current for an Arduino pin. Here we have 4 LEDs drawing 20 mA each.
Each Arduino pin can handle 40 mA of current. A seperate power supply is also needed.
*/
int ledPinA = 5;
int i=0;
int s=1;
int buttonPin = 2;
int ledPin = 7;
int buttonState = 0;
int ledState=1;// 1 = Glow, 2 = Pulse
long previousMillis = 0;
long interval = 100;
void setup()
{
Serial.begin(9600);
pinMode(ledPinA, OUTPUT);
pinMode(ledPin,OUTPUT);
attachInterrupt(0, blink, CHANGE); // pushbutton switch connected to pin 2
}
void loop()
{
switch (ledState) {
case 1:
lightGlow();
break;
case 2:
lightPulse();
break;
}
}
void lightGlow()
{
Serial.println("Glow ");
digitalWrite(ledPinA, HIGH);
}
void lightPulse()
{
Serial.println("Pulse ");
for (i=0; i<255; i++)
{
analogWrite(ledPinA, 255-i);
delay(100);
}
for (i=0; i<255; i++)
{
analogWrite(ledPinA, i);
delay(100);
}
}
void lightPulse2()
{
Serial.println("Pulse ");
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval)
{
previousMillis = currentMillis;
i++;
}
if (i>=255 && s==1)
{
s=0;
i=0;
}
else if (i>=255)
{
s=1;
i=0;
}
if (s==0)
{
analogWrite(ledPinA, 255-i);
}
if (s==1)
{
analogWrite(ledPinA, i);
}
}
void blink()
{
if (ledState == 2)
{
digitalWrite(ledPin, LOW);
ledState=1; //Pulse mode
}
else
{
digitalWrite(ledPin, HIGH);
ledState=2; //Glow mode
}
}
void buttonRead()
{
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH)
{
digitalWrite(ledPin, HIGH);
ledState=2; //Pulse mode
}
else
{
digitalWrite(ledPin, LOW);
ledState=1; //Glow mode
}
switch (ledState)
{
case 1:
lightGlow();
break;
case 2:
lightPulse();
break;
}
}
Here is my function with the delay. This works fine expect I want it without the delay.
void lightPulse()
{
Serial.println("Pulse ");
for (i=0; i<250; i++)
{
analogWrite(ledPinA, 255-i);
delay(100);
}
for (i=5; i<255; i++)
{
analogWrite(ledPinA, i);
delay(100);
}
}
Here is my attempt to make it without the delay. I have not actually tested this yet.
void lightPulse2()
{
Serial.println("Pulse ");
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval)
{
previousMillis = currentMillis;
i++;
}
if (i>=255 && s==1)
{
s=0;
i=0;
}
else if (i>=255)
{
s=1;
i=0;
}
if (s==0)
{
analogWrite(ledPinA, 255-i);
}
if (s==1)
{
analogWrite(ledPinA, i);
}
}
Will this work? How would I make it better / more simplified?
Thanks.