Code
Since this project requires 3 PWM, but in RPi, only one GPIO has the hardware capability to output PWM, we
need to use the software to make the ordinary GPIO output PWM.
C Code 5.1.1 ColorfulLED
First observe the project result, and then analyze the code.
1. Use cd command to enter 05.1.1_ColorfulLED directory of C code.
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/C_Code/05.1.1_ColorfulLED
2. Use following command to compile “ColorfulLED.c” and generate executable file “ColorfulLED”. Note: in
this project, the software PWM uses a multi-threading mechanism. So “-lpthread” option need to be add
the compiler.
gcc ColorfulLED.c -o ColorfulLED -lwiringPi -lpthread
3. And then run the generated by “ColorfulLED”.
sudo ./ColorfulLED
After the program is executed, you will see that the RGBLED shows light of different color randomly.
The following is the program code:
#include <wiringPi.h>
#include <softPwm.h>
#include <stdio.h>
#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(int r_val, int g_val, int b_val)
{
softPwmWrite(ledPinRed, r_val);
softPwmWrite(ledPinGreen, g_val);
softPwmWrite(ledPinBlue, b_val);
}
int main(void)
{
int r,g,b;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print message to screen
printf("setup wiringPi failed !");