标签:raspberry pi rgb led 树莓派 softpwm wiringpi
用树莓派实现RGB LED的颜色控制
RGB色彩模式是工业界的一种颜色标准,是通过对红(R)、绿(G)、蓝(B)三个颜色通道的变化以及它们相互之间的叠加来得到各式各样的颜色的,RGB即是代 表红、绿、蓝三个通道的颜色,这个标准几乎包括了人类视力所能感知的所有颜色,是目前运用最广的颜色系统之一。RGB色彩模式使用RGB模型为图像中每一个像素的RGB分量分配一个0~255范围内的强度值。RGB图像只使用三种颜色,就可以使它们按照不同的比例混合,从而得到各种各样的颜色。
在实际的控制中,往往通过PWM来实现LED亮度(颜色深度)的控制。
树莓派只有一路硬件PWM输出(GPIO1),可是要实现RGB LED的控制,需要3路PWM。其实,wiringPi库为我们提供了用软件多线程实现的PWM输出,我们可以利用这个库提供的函数很方便的将任意GPIO配置为PWM输出。在本例中,我将GPIO0,GPIO1,GPIO2配置成了soft PWM输出。树莓派的引脚分配表如下图所示:
我用的RGB LED是共阴极的,与树莓派的连接方式如下:
Raspberry Pi RGB LED module
GPIO0 -------------------------------------- R
GPIO1 ------------------------------------- G
GPIO2 -------------------------------------- B
GND ---------------------------------------- ‘-’
实物图如下:
源代码:
#include <wiringPi.h>
#include <softPwm.h>
#include <stdio.h>
#define uchar unsigned char
#define LedPinRed 0
#define LedPinGreen 1
#define LedPinBlue 2
void ledInit(void)
{
softPwmCreate(LedPinRed, 0, 100);
softPwmCreate(LedPinGreen,0, 100);
softPwmCreate(LedPinBlue, 0, 100);
}
void ledColorSet(uchar r_val, uchar g_val, uchar b_val)
{
softPwmWrite(LedPinRed, r_val);
softPwmWrite(LedPinGreen, g_val);
softPwmWrite(LedPinBlue, b_val);
}
int main(void)
{
int i;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print message to screen
printf("setup wiringPi failed !");
return 1;
}
ledInit();
while(1){
ledColorSet(0xff,0x00,0x00); //red
delay(500);
ledColorSet(0x00,0xff,0x00); //green
delay(500);
ledColorSet(0x00,0x00,0xff); //blue
delay(500);
ledColorSet(0xff,0xff,0x00); //yellow
delay(500);
ledColorSet(0xff,0x00,0xff); //pick
delay(500);
ledColorSet(0xc0,0xff,0x3e);
delay(500);
ledColorSet(0x94,0x00,0xd3);
delay(500);
ledColorSet(0x76,0xee,0x00);
delay(500);
ledColorSet(0x00,0xc5,0xcd);
delay(500);
}
return 0;
}
将此代码保存为rgb.c。
编译代码:
gcc rgb.c -o rgb -lwiringPi -lpthread
运行代码:
./rgb
注意:
1,-lwiringPi选项:指明了要链接到wiringpi库,因为softPwm的实现就在此库;
2,-lpthread选项:因为softPwm的实现用了Linux的多线程机制,所以加这个编译选项。
代码和演示视频已分享到360云盘:
点我下载代码 访问密码e0da
点我下载视频 访问密码d6b1
用树莓派实现RGB LED的颜色控制,布布扣,bubuko.com
标签:raspberry pi rgb led 树莓派 softpwm wiringpi
原文地址:http://blog.csdn.net/jcdjx/article/details/38457271