Skip to content

Instantly share code, notes, and snippets.

@MichMich
Last active November 5, 2023 16:48
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 MichMich/32ca143709ef9391f1f16c88a824188e to your computer and use it in GitHub Desktop.
Save MichMich/32ca143709ef9391f1f16c88a824188e to your computer and use it in GitHub Desktop.
AtTiny10 WS2812 Test
#include <avr/io.h>
#include <util/delay.h>
#include <stdint.h>
#include <avr/interrupt.h>
#define bitRead(value, bit) (((value) >> (bit)) & 0x01)
#define bitSet(value, bit) ((value) |= (1UL << (bit)))
#define delay(ms) _delay_ms(ms)
#define PIN 2
void setup() {
// Set the clock speed of the ATTiny10 to 8mhz.
CCP = 0xD8;
CLKPSR = 0;
// Set all ports to output.
DDRB = 0b1111;
}
void sendBit( bool bitVal ) {
if (bitVal) {
asm volatile (
"sbi %[port], %[bit] \n"
"nop \n nop \n nop \n nop \n nop \n nop \n"
"cbi %[port], %[bit] \n"
"nop \n "
::
[port] "I" (_SFR_IO_ADDR(PORTB)),
[bit] "I" (PIN)
);
} else {
asm volatile (
"sbi %[port], %[bit] \n"
"nop \n "
"cbi %[port], %[bit] \n"
"nop \n nop \n nop \n nop \n nop \n nop \n"
::
[port] "I" (_SFR_IO_ADDR(PORTB)),
[bit] "I" (PIN)
);
}
}
void sendByte( unsigned char byte ) {
for( unsigned char bit = 0 ; bit < 8 ; bit++ ) {
sendBit( bitRead( byte , 7 ) );
byte <<= 1;
}
}
void sendPixel( unsigned char r, unsigned char g , unsigned char b ) {
cli(); // Disable Interrupts
sendByte(g);
sendByte(r);
sendByte(b);
sei(); // Enable Interrupts
}
void show() {
_delay_us(350);
}
void wheelColor(unsigned char wheelPosition, unsigned char &r, unsigned char &g, unsigned char &b) {
wheelPosition = 255 - wheelPosition;
if(wheelPosition < 85) {
r = 255 - wheelPosition * 3;
g = 0;
b = wheelPosition * 3;
return;
}
if(wheelPosition < 170) {
wheelPosition -= 85;
r = 0;
g = wheelPosition * 3;
b = 255 - wheelPosition * 3;
return;
}
wheelPosition -= 170;
r = wheelPosition * 3;
g = 255 - wheelPosition * 3;
b = 0;
}
void loop() {
for (unsigned char wheelPos = 0; wheelPos <= 255; wheelPos++) {
unsigned char r;
unsigned char g;
unsigned char b;
wheelColor(wheelPos, r, g, b);
// Send the data twice, due to the skipping of the 24 bits as described in the blog post:
// http://michaelteeuw.nl/post/179174194937/a-tiny-mistery-the-odd-leds
sendPixel(r, g, b);
sendPixel(r, g, b);
show();
delay(10);
}
}
int main() {
setup();
for(;;) loop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment