用C语言写WS2812 RGB灯带控制例程代码
时间: 2023-06-02 11:08:34 浏览: 300
WS2812灯带驱动代码teszt.rar
5星 · 资源好评率100%
好的,我可以为您提供一个用C语言编写的WS2812 RGB灯带控制例程代码。以下是代码:
#include <stdint.h>
#include <stdio.h>
#define LED_COUNT 12
#define LED_PIN 7
void sendBit(uint8_t bit){
if(bit){
// Send '1' bit. 70% ON, 30% OFF
TCCR0A = _BV(WGM01) | _BV(COM0A1) | _BV(COM0A0);
_delay_us(22);
// Clear output
TCCR0A = 0;
_delay_us( 38);
} else {
// Send '0' bit. 30% ON, 70% OFF
TCCR0A = _BV(WGM01) | _BV(COM0A1) | _BV(COM0A0);
_delay_us( 9);
// Clear output
TCCR0A = 0;
_delay_us( 81);
}
}
void sendByte(uint8_t byte){
for(uint8_t i=0;i<8;++i){
sendBit(byte&0x80);
byte<<=1;
}
}
void sendColor(uint8_t r,uint8_t g,uint8_t b){
sendByte(g);
sendByte(r);
sendByte(b);
}
void sendBuffer(uint8_t *ptr){
for(uint8_t i=0;i<LED_COUNT;++i){
sendColor(ptr[3*i+0],ptr[3*i+1],ptr[3*i+2]);
}
}
void led_init(){
TCCR0A = _BV(WGM01); // Toggle OC0A on compare match
TCCR0B = _BV(CS00); // No prescaler
DDRD |= _BV(DDD6); // PD6 as output
TCCR0A = 0; // Clear output
}
void led_on(){
TCCR0A = _BV(COM0A1) | _BV(COM0A0); // Set output high
}
void led_off(){
TCCR0A = 0; // Set output low
}
void setLedColor(uint8_t *buffer){
cli();
led_on();
_delay_us(60);
sendBuffer(buffer);
_delay_us(60);
led_off();
sei();
}
int main(){
uint8_t buffer[LED_COUNT*3];
led_init(); // Initialize timer for 800kHz PWM output
while(1){
// Set all LEDs to red
for(uint8_t i=0;i<LED_COUNT;++i){
buffer[3*i+0] = 255; // Red
buffer[3*i+1] = 0; // Green
buffer[3*i+2] = 0; // Blue
}
setLedColor(buffer); // Send the buffer to the LEDs
_delay_ms(500); // Wait half a second
// Set all LEDs to green
for(uint8_t i=0;i<LED_COUNT;++i){
buffer[3*i+0] = 0; // Red
buffer[3*i+1] = 255; // Green
buffer[3*i+2] = 0; // Blue
}
setLedColor(buffer); // Send the buffer to the LEDs
_delay_ms(500); // Wait half a second
// Set all LEDs to blue
for(uint8_t i=0;i<LED_COUNT;++i){
buffer[3*i+0] = 0; // Red
buffer[3*i+1] = 0; // Green
buffer[3*i+2] = 255; // Blue
}
setLedColor(buffer); // Send the buffer to the LEDs
_delay_ms(500); // Wait half a second
}
return 0;
}
阅读全文