bcm2835 1.75
pwm.c

Shows how to use PWM to control GPIO pins

// pwm.c
//
// Example program for bcm2835 library
// Shows how to use PWM to control GPIO pins
//
// After installing bcm2835, you can build this
// with something like:
// gcc -o pwm pwm.c -l bcm2835
// sudo ./pwm
//
// Or you can test it before installing with:
// gcc -o pwm -I ../../src ../../src/bcm2835.c pwm.c
// sudo ./pwm
//
// Connect an LED between GPIO18 (pin 12) and GND to observe the LED changing in brightness
//
// Author: Mike McCauley
// Copyright (C) 2013 Mike McCauley
// $Id: RF22.h,v 1.21 2012/05/30 01:51:25 mikem Exp $
#include <bcm2835.h>
#include <stdio.h>
// PWM output on RPi Plug P1 pin 12 (which is GPIO pin 18)
// in alt fun 5.
// Note that this is the _only_ PWM pin available on the RPi IO headers
#define PIN RPI_GPIO_P1_12
// and it is controlled by PWM channel 0
#define PWM_CHANNEL 0
// This controls the max range of the PWM signal
#define RANGE 1024
int main(int argc, char **argv)
{
if (!bcm2835_init())
return 1;
// Set the output pin to Alt Fun 5, to allow PWM channel 0 to be output there
// Clock divider is set to 16.
// With a divider of 16 and a RANGE of 1024, in MARKSPACE mode,
// the pulse repetition frequency will be
// 1.2MHz/1024 = 1171.875Hz, suitable for driving a DC motor with PWM
bcm2835_pwm_set_clock(BCM2835_PWM_CLOCK_DIVIDER_16);
bcm2835_pwm_set_mode(PWM_CHANNEL, 1, 1);
bcm2835_pwm_set_range(PWM_CHANNEL, RANGE);
// Vary the PWM m/s ratio between 1/RANGE and (RANGE-1)/RANGE
// over the course of a a few seconds
int direction = 1; // 1 is increase, -1 is decrease
int data = 1;
while (1)
{
if (data == 1)
direction = 1; // Switch to increasing
else if (data == RANGE-1)
direction = -1; // Switch to decreasing
data += direction;
bcm2835_pwm_set_data(PWM_CHANNEL, data);
}
return 0;
}
@ BCM2835_GPIO_FSEL_ALT5
Definition: bcm2835.h:895
void bcm2835_delay(unsigned int millis)
Definition: bcm2835.c:539
void bcm2835_gpio_fsel(uint8_t pin, uint8_t mode)
Definition: bcm2835.c:302
int bcm2835_close(void)
Definition: bcm2835.c:2163
int bcm2835_init(void)
Definition: bcm2835.c:2008
void bcm2835_pwm_set_clock(uint32_t divisor)
Definition: bcm2835.c:1900
void bcm2835_pwm_set_data(uint8_t channel, uint32_t data)
Definition: bcm2835.c:1968
void bcm2835_pwm_set_mode(uint8_t channel, uint8_t markspace, uint8_t enabled)
Definition: bcm2835.c:1919
void bcm2835_pwm_set_range(uint8_t channel, uint32_t range)
Definition: bcm2835.c:1956