RGB LED With ATtiny85 Part 2
I’ve updated my script and removed the pot from my design, so that now it just fades between random colours on its own, using an LDR to tell if its dark enough to turn on or so light that it should turn itself off as you wouldn’t see the LED anyway:
// init vars
const int REDPIN = 1; // 85 leg 6
const int GREENPIN = 0; // 85 leg 5
const int BLUEPIN = 4; // 85 leg 3
const int LDR = 3; // 85 leg 2
const int THRESHOLD = 200;
int last_time;
int red;
int green;
int blue;
int current_red;
int current_green;
int current_blue;
void doFade(int pin, int &val, int ¤t_val)
{
// val and current_val are passed as references
// so modifying them will actually modify e.g.
// red and current_red without having to return them
if (val > current_val)
{
current_val++;
analogWrite(pin, current_val);
delay(10);
}
else if (val < current_val)
{
current_val--;
analogWrite(pin, current_val);
delay(10);
}
else
{
analogWrite(pin, current_val);
val = random(255);
}
}
void setup()
{
// read from unconnected pin for entropy
randomSeed(analogRead(2));
// setup pin directions
pinMode(REDPIN, OUTPUT);
pinMode(GREENPIN, OUTPUT);
pinMode(BLUEPIN, OUTPUT);
pinMode(LDR, INPUT);
}
void loop()
{
// fetch current uptime
int this_time = millis();
// is ldr reading higher (brighter) than our threshold?
if (analogRead(LDR) > THRESHOLD)
{
// is it more than 5secs since it was last dark?
if (this_time - last_time > 5000)
{
// turn off the led as its not dark
analogWrite(REDPIN, 0);
analogWrite(GREENPIN, 0);
analogWrite(BLUEPIN, 0);
}
}
else
{
// call fade function for each colour
doFade(REDPIN, red, current_red);
doFade(GREENPIN, green, current_green);
doFade(BLUEPIN, blue, current_blue);
// reset the counter
last_time = this_time;
}
}
I’ve soldered the final design onto veroboard after prototyping on breadboard: