RGB LED Fader
From PaulJMac
Abstract
This is a neat little thing that will generate a very smooth fading RGB LED. I used these little ShiftBright modules which have the A6281 already mounted along with an RGB LED. I don't have the ability to solder a 3mm x 3mm QFN myself.
Parts
Code
main.c
#include <avr/io.h>
#include <util/delay.h>
#define bit_get(p,m) ((p) & (m))
#define bit_set(p,m) ((p) |= (m))
#define bit_clear(p,m) ((p) &= ~(m))
#define bit_flip(p,m) ((p) ^= (m))
#define bit_write(c,p,m) (c ? bit_set(p,m) : bit_clear(p,m))
#define BIT(x) (0x01 << (x))
#define LONGBIT(x) ((unsigned long)0x00000001 << (x))
#define NOP asm("nop")
#define E_S bit_set(PORTA,BIT(0));
#define E_C bit_clear(PORTA,BIT(0)); //OE is active low, this turns lights on
#define L_S bit_set(PORTA,BIT(1));
#define L_C bit_clear(PORTA,BIT(1));
#define LED_OFF bit_clear(PORTA,BIT(7));
#define LED_ON bit_set(PORTA,BIT(7));
#define shift USICR|=(1<<USICLK); //generates a shift in the SPI register
#define clock USICR|=(1<<USITC); //generates a clock on the SPI bus
//PA1 is Latch inout
//PA0 is Enable output
volatile uint8_t x=0;
void Port_setup(void){
DDRA|=(1<<PA7)|(0<<PA6)|(1<<PA5)|(1<<PA4)|(1<<PA1)|(1<<PA0); //seting up the apropriate SPI i/o's
USICR|=(0<<USIWM1)|(1<<USIWM0)|(0<<USICS1)|(0<<USICS0); //SPI mode
DDRB|=(0<<PB1);
PORTB|=(1<<PORTB0);
LED_OFF;
E_C;
L_C;
}
void shft8bit(unsigned char val)
{
USIDR = val;
USISR = (1<<USIOIF);
do {
USICR = (1<<USIWM0)|(1<<USICS1)|(1<<USICLK)|(1<<USITC);
_delay_us(40);
} while ((USISR & (1<<USIOIF)) == 0);
}
void colors(uint16_t red, uint16_t green, uint16_t blue)
{
volatile uint32_t packet=1;
packet = (packet << 2)| (blue & 1023);
packet = (packet << 10)| (red & 1023);
packet = (packet << 10)| (green & 1023);
shft8bit((packet>>24) & 0xff);
shft8bit((packet>>16) & 0xff);
shft8bit((packet>>8) & 0xff);
shft8bit((packet>>0) & 0xff);
L_S;
_delay_us(40);
L_C;
}
void LED_setup(void)
{
shft8bit(0b11111111);
shft8bit(0b11111111);
shft8bit(0b11111111);
shft8bit(0b00111111);
L_S;
_delay_us(40);
L_C;
}
void Blue(void)
{
// blue
shft8bit(0b10111111);
shft8bit(0b11110000);
shft8bit(0b00000000);
shft8bit(0b00000000);
L_S;
_delay_us(40);
L_C;
}
void Red(void)
{
// red
shft8bit(0b10000000);
shft8bit(0b00001111);
shft8bit(0b11111100);
shft8bit(0b00000000);
L_S;
_delay_us(40);
L_C;
}
void Green(void)
{
// green
shft8bit(0b10000000);
shft8bit(0b00000000);
shft8bit(0b00000011);
shft8bit(0b11111111);
L_S;
_delay_us(40);
L_C;
}
void Clear(void)
{
// green
shft8bit(0b10000000);
shft8bit(0b00000000);
shft8bit(0b00000000);
shft8bit(0b00000000);
L_S;
_delay_us(40);
L_C;
}
void Delay(void)
{
_delay_ms(40);
}
int main (void)
{
E_S;
Delay();
Port_setup();
LED_setup();
Clear();
Clear();
E_C;
LED_ON;
for(;;)
{
int y=0;
for(int i=1023;i>0;i--)
{
y++;
colors(i,y,0);
Delay();
}
y=0;
for(int i=1023;i>0;i--)
{
y++;
colors(0,i,y);
Delay();
}
y=0;
for(int i=1023;i>0;i--)
{
y++;
colors(y,0,i);
Delay();
}
}
}