How to do it...

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:

  1. In your ~/test working directory, create a subdirectory called pwm.
  2. Use your favorite text editor to create a pwm.cpp file in the pwm subdirectory.
  3. 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) ;
}
  1. 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 ;
}
  1. 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)
  1. Connect an LED to your Raspberry Pi board using the instructions from the WiringPI example section at http://wiringpi.com/examples/blink/.
  2. 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/.
  3. Copy the contents of the pwm folder to the Raspberry Pi board over SSH.
  4. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.96.146