We are going to create a simple application that gradually changes the brightness of an LED connected to a general-purpose pin on a Raspberry Pi board:
- In your ~/test working directory, create a subdirectory called pwm.
- Use your favorite text editor to create a pwm.cpp file in the pwm subdirectory.
- Let's put in the required include functions and define a function called Blink:
#include <chrono>
#include <thread>
#include <wiringPi.h>
using namespace std::literals::chrono_literals;
const int kLedPin = 0;
void Blink(std::chrono::microseconds duration, int percent_on) {
digitalWrite (kLedPin, HIGH);
std::this_thread::sleep_for(
duration * percent_on / 100) ;
digitalWrite (kLedPin, LOW);
std::this_thread::sleep_for(
duration * (100 - percent_on) / 100) ;
}
- This is followed by a main function:
int main (void)
{
if (wiringPiSetup () <0) {
throw std::runtime_error("Failed to initialize wiringPi");
}
pinMode (kLedPin, OUTPUT);
int count = 0;
int delta = 1;
while (true) {
Blink(10ms, count);
count = count + delta;
if (count == 101) {
delta = -1;
} else if (count == 0) {
delta = 1;
}
}
return 0 ;
}
- Create a CMakeLists.txt file containing the build rules for our program:
cmake_minimum_required(VERSION 3.5.1)
project(pwm)
add_executable(pwm pwm.cpp)
target_link_libraries(pwm wiringPi)
- Connect an LED to your Raspberry Pi board using the instructions from the WiringPI example section at http://wiringpi.com/examples/blink/.
- Set up an SSH connection to your Raspberry Pi board. Follow instructions from the Raspberry PI documentation section at https://www.raspberrypi.org/documentation/remote-access/ssh/.
- Copy the contents of the pwm folder to the Raspberry Pi board over SSH.
- Log in to the board over SSH, then build and run the application:
$ cd pwm && cmake . && make && sudo ./pwm
Your application should now run and you can observe the LED blinking.