5

In one application we are using the raspberry p to control motor speed via PWM. We were able to get a valid working code on the raspberry pi 2, but when we transferred this code and drivers over to the pi 3 the code simply does not work. Is there any easy thing we are missing in switching from the pi 2 to the pi 3 to get this code working?

#include <bcm2835.h>
#include <stdio.h>

#define PIN RPI_BPLUS_GPIO_J8_32
#define PIN2 RPI_BPLUS_GPIO_J8_33
#define CTL_PIN RPI_BPLUS_GPIO_J8_29
#define CTL_PIN2 RPI_BPLUS_GPIO_J8_31

#define PWM_CHANNEL 0
#define PWM_CHANNEL2 1

#define RANGE 1024

int main(int argc, char **argv)
{
//      bcm2835_delay(10000);
    if (!bcm2835_init())
     return 1;

    // Set the output pin to Alt Fun 5, to allow PWM channel 0 to be output    there
    bcm2835_gpio_fsel(PIN, BCM2835_GPIO_FSEL_ALT0);
    bcm2835_gpio_fsel(PIN2, BCM2835_GPIO_FSEL_ALT0);
    bcm2835_gpio_fsel(CTL_PIN, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(CTL_PIN2, BCM2835_GPIO_FSEL_OUTP);

    // 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);
    bcm2835_pwm_set_mode(PWM_CHANNEL2, 1, 1);
    bcm2835_pwm_set_range(PWM_CHANNEL2, RANGE);

    // Vary the PWM m/s ratio between 1/RANGE and (RANGE-1)/RANGE
    int direction = 1;
    int data = 1;
    int j;
    bcm2835_gpio_write(CTL_PIN, HIGH);
    bcm2835_gpio_write(CTL_PIN2, HIGH);

    for (j=0;j<4096;j++)
      {
        if (j==2048) {
          bcm2835_gpio_write(CTL_PIN, LOW);
//        bcm2835_gpio_write(CTL_PIN2, LOW);
        }
    if (data == 1)
      direction = 1;
    else if (data == RANGE-1)
      direction = -1;
    data += direction;
      bcm2835_pwm_set_data(PWM_CHANNEL, data);
      bcm2835_pwm_set_data(PWM_CHANNEL2, data);
    bcm2835_delay(10);
      }
      bcm2835_pwm_set_data(PWM_CHANNEL, 0);
      bcm2835_pwm_set_data(PWM_CHANNEL2, 0);

    bcm2835_close();
    return 0;
}
joan
  • 71,852
  • 5
  • 76
  • 108
Sean
  • 51
  • 1
  • 2

2 Answers2

1

Here's the relevant thread for this problem- https://groups.google.com/forum/#!searchin/bcm2835/pwm$20not$20working%7Csort:relevance/bcm2835/mZjLtVmlKV8/d1BheSSKAgAJ

According to the discussion, you'd need to have sudo/root permissions while running the C executable for the PWM to work.

0

I had the same problem just now! At the end I discovered that the GPIO18 works properly while GPIO12 does not work (there is no PWM signal).

Just change:

#define PIN RPI_GPIO_P1_12

by

#define PIN RPI_GPIO_P1_18

Thats all.

omotto
  • 111
  • 2