Skip to content

Instantly share code, notes, and snippets.

@peppy
Created June 6, 2014 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peppy/0b4694d08f4053d44382 to your computer and use it in GitHub Desktop.
Save peppy/0b4694d08f4053d44382 to your computer and use it in GitHub Desktop.
#include <SPI.h>
#define LED_COUNT 160
#define CSPIN 9
#define PACKET_SIZE (LED_COUNT * 3)
uint8_t buffer[PACKET_SIZE];
void setup()
{
Serial.begin(576000);
Serial.setTimeout(1);
pinMode(CSPIN, OUTPUT);
digitalWrite(CSPIN, LOW);
SPI.begin();
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
SPI.setClockDivider(SPI_CLOCK_DIV8);
for (int i = 0; i < LED_COUNT * 3; i++)
buffer[i] = 0;
}
int negotiated = 0;
const int timeout_length = 2000;
uint8_t aimR = 0, aimG = 0, aimB = 0, currentR = 0, currentG = 0, currentB = 0;
void outputRandom()
{
if (aimR == currentR && aimG == currentG && aimB == currentB)
{
aimR = random(255);
aimG = random(255);
aimB = random(255);
}
if (currentR != aimR) currentR = aimR > currentR ? currentR + 1 : currentR - 1;
if (currentG != aimG) currentG = aimG > currentG ? currentG + 1 : currentG - 1;
if (currentB != aimB) currentB = aimB > currentB ? currentB + 1 : currentB - 1;
int index = 0, length = LED_COUNT * 3;
while(index < length) {
buffer[index] = currentB;
buffer[index + 1] = currentG;
buffer[index + 2] = currentR;
index += 3;
}
}
int readBytes = 0;
void loop()
{
while (true)
{
int available = Serial.available();
if (available > 0) {
while (available-- > 0 && readBytes < PACKET_SIZE)
buffer[readBytes++] = Serial.read();
negotiated = timeout_length;
}
else if (negotiated > 0)
{
negotiated--;
delay(1);
}
else
{
outputRandom();
Serial.println(LED_COUNT);
delay(50);
}
if (readBytes == PACKET_SIZE || !negotiated)
{
int i, length = LED_COUNT * 3;
readBytes = 0;
digitalWrite(CSPIN, HIGH);
for(i = 0; i < length; i++)
{
SPDR = buffer[i];
while(!(SPSR & (1 << SPIF)));
}
digitalWrite(CSPIN, LOW);
delay(1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment