Hey guys;
OK, the code is pretty simple, it follows the normal PWM pattern for the most part, the one problem is, my code freezes up when I try to shiftOut a (2 byte) Short with a slightly modified shiftOut() function. Can anybody help me with this?
Also, if you see any way to let the ISR run more faster, could you point it out?
Thanks guys! If you need any more info, feel free to ask. Ill do my best!
#define __dataPin 9
#define __clockPin 10
#define __latchPin 11
#define __numLedsInArray 4
#define __numPinsPerLed 3
#define __maxBrightness 100
int ledPin = 13; // LED connected to digital pin 13
int i=0;
int tcnt2;
int isrCount = 0;
int loopCount=2;
int ledStates[__numLedsInArray][__numPinsPerLed];
int ledNumber = 0;
int ledLoopNum = 0;
short currBuffer = 0;
void setup() {
// initialize the shift reg control pins as outputs:
pinMode(__dataPin, OUTPUT);
pinMode(__clockPin, OUTPUT);
pinMode(__latchPin, OUTPUT);
Serial.begin(9600);
setupTimer();
}
ISR(TIMER2_OVF_vect) {
/* Reload the timer */
TCNT2 = 160; //This seems to not flicker very much.
while(ledNumber <= __numLedsInArray-1)
{
while(loopCount<=2)
{
if(ledStates[ledNumber][loopCount] <= isrCount)
{
currBuffer |= (1<<loopCount+(ledNumber*3));
}
else
{
currBuffer &= ~(1<<loopCount+(ledNumber*3));
}
loopCount++;
}
loopCount=0;
ledNumber++;
}
ledNumber=0;
digitalWrite(__latchPin, LOW);
shiftOutTwoBytes(__dataPin, __clockPin, LSBFIRST, currBuffer);
digitalWrite(__latchPin, HIGH);
isrCount++;
if(isrCount >= 100)
{
isrCount=0;
}
}
void setupTimer() //Set up the timer.
{
unsigned int tcnt2;
TIMSK2 &= ~(1<<TOIE2);
TCCR2A &= ~((1<<WGM21) | (1<<WGM20));
TCCR2B &= ~(1<<WGM22);
ASSR &= ~(1<<AS2);
TIMSK2 &= ~(1<<OCIE2A);
TCCR2B |= (1<<CS22) | (1<<CS21) | (1<<CS20); // Set bits
//
//TCCR2B &= ~(1<<CS21); // Clear bit
//TCCR2B &= ~(1<<CS20);
TCCR2B &= ~(1<<CS22); //Clearing only this gives best timing.
TIMSK2 |= (1<<TOIE2);
}
void loop()
{
//This fades in and out the individual colors in 2 LED's.
while(ledLoopNum <=2) //Do first LED
{
i=0;
while(i<=100)
{
ledStates[0][ledLoopNum]=i;
i++;
delay(3);
}
i=100;
while(i>=0)
{
ledStates[0][ledLoopNum]=i;
i--;
delay(3);
}
ledLoopNum++;
}
ledLoopNum=0;
while(ledLoopNum <=2) //Do second LED
{
i=0;
while(i<=100)
{
ledStates[1][ledLoopNum]=i;
i++;
delay(3);
}
i=100;
while(i>=0)
{
ledStates[1][ledLoopNum]=i;
i--;
delay(3);
}
ledLoopNum++;
}
ledLoopNum=0;
}
void shiftOutTwoBytes(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, short val)
{
int i;
for (i = 0; i < 16; i++) {
digitalWrite(dataPin, !!(val & (1 << i)));
digitalWrite(clockPin, HIGH);
digitalWrite(clockPin, LOW);
}
}