Skip to content

Instantly share code, notes, and snippets.

@jenschr
Last active January 5, 2019 20:55
Show Gist options
  • Save jenschr/3903ba73f447500e17497e05d34712fa to your computer and use it in GitHub Desktop.
Save jenschr/3903ba73f447500e17497e05d34712fa to your computer and use it in GitHub Desktop.
APA102 on STM32F070F6
/*
* Simplified code for running APA-102 on STM32
* (or most any other platform by replacing the
* sendRaw-method with platform SPI calls)
*/
#define NUMBER_OF_LEDS 46 // Define number of LEDs in the chain
#define COLORS_PER_LED 3 // Define number of colors we store
const int bufferLength = NUMBER_OF_LEDS*3;
uint8_t ledBuffer[NUMBER_OF_LEDS*COLORS_PER_LED];
void sendRaw(uint8_t data) {
HAL_SPI_Transmit(&hspi1, &data, 1, 1000);
}
void update() {
// StartFrame (0x00000000)
sendRaw(0x00);
sendRaw(0x00);
sendRaw(0x00);
sendRaw(0x00);
// Loop over all the LEDs
for (int led = 0; led < NUMBER_OF_LEDS; led++) {
int ledNum = led*3;
// For POV, we always want full intensity (31 brightness), so we send the first 8 bits as 0xFF
// the 3 INIT bits should always be 0xE0 (11100000) + the brightness bits should also all be ones 0x1F (00011111) = 0xFF
sendRaw((uint8_t) (0xFF) );
sendRaw((uint8_t) (ledBuffer[ledNum])); // Send BLUE
sendRaw((uint8_t) (ledBuffer[ledNum+1])); // Send GREEN
sendRaw((uint8_t) (ledBuffer[ledNum+2])); // Send RED
}
// EndFrame (0xffffffff)
sendRaw(0xff);
sendRaw(0xff);
sendRaw(0xff);
sendRaw(0xff);
// Note that if you have a lot of LEDs, check this post at Tim's blog:
// https://cpldcpu.wordpress.com/2014/11/30/understanding-the-apa102-superled/
}
uint8_t TestPosition(const uint8_t led) {
uint8_t returnValue = OUT_OF_RANGE;
if (led < bufferLength) {
returnValue = RANGE_OK;
}
return returnValue;
}
// Smooth rainbow color code from Adafruit. Thanks for always helping the community!
void setColor( uint8_t led, uint8_t red, uint8_t green, uint8_t blue ) {
int ledNum = led*3;
if (TestPosition(ledNum) == RANGE_OK) {
ledBuffer[ledNum] = blue;
ledBuffer[ledNum+1] = green;
ledBuffer[ledNum+2] = red;
}
}
void setRGB( uint8_t led, uint32_t rgb)
{
setColor(led, (uint8_t)(rgb), (uint8_t)(rgb >> 8), (uint8_t)(rgb >> 16 ));
}
uint32_t Color(uint8_t r, uint8_t g, uint8_t b) {
return ((uint32_t)b << 16) | ((uint32_t)g << 8) | r;
}
uint32_t Wheel(uint8_t WheelPos) {
uint32_t result = 0;
WheelPos = 255 - WheelPos;
if(WheelPos < 85) {
result = Color(255 - WheelPos * 3, 0, WheelPos * 3);
} else if(WheelPos < 170) {
WheelPos -= 85;
result = Color(0, WheelPos * 3, 255 - WheelPos * 3);
} else {
WheelPos -= 170;
result = Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}
return result;
}
void rainbow(uint8_t wait) {
uint16_t i, j;
for (j = 0; j < 256; j++) {
for (i = 0; i < NUMBER_OF_LEDS; i++) {
setRGB(i, Wheel((i + j) & 255) );
}
update();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment