2

I've got a Raspberry Pi 3B with which I want to control a motor using PWM. In Python this works great to gradually increase the voltage of a GPIO pin from 0% to 100% (100% == 3.3V):

import RPi.GPIO as GPIO
from time import sleep

PWM_PIN = 13

GPIO.setmode(GPIO.BCM)
GPIO.setup(PWM_PIN, GPIO.OUT)

p = GPIO.PWM(PWM_PIN, 1000)
p.start(0)

for i in range(101):
    print(i)
    p.ChangeDutyCycle(i)
    sleep(0.1)

sleep(5)  # Keep the voltage at 100% for 5 seconds, after which the program ends

Since I'm writing my program in Go I now want to do the same thing (or similar) in Go. So this is my shot at it.

package main

import (
    "fmt"
    "time"
    rpio "github.com/stianeikeland/go-rpio"
)

const (
    PWM_PIN = 13
)

func main() {
    err := rpio.Open()
    if err != nil {
        panic(err)
    }

    motor_pin_pwm := rpio.Pin(PWM_PIN)
    motor_pin_pwm.Mode(rpio.Pwm)
    motor_pin_pwm.Freq(1000)
    motor_pin_pwm.DutyCycle(0, 100)
    
    fmt.Println("Waiting...")
    time.Sleep(5 * time.Second)
    fmt.Println("Start the increase...")

    for i := 1; i <= 100; i++ {
        fmt.Println(i)
        motor_pin_pwm.DutyCycle(uint32(i), 100)
        time.Sleep(100 * time.Millisecond)
    }
    time.Sleep(5 * time.Second)
}

There's an example of using go-rpio to control PWM here. The example is meant to control a LED instead of a motor, but I guess the code should be very similar (if not the same). The example uses different values, so I messed around with the values a bit but with no results.

What am I missing here?

halfer
  • 19,824
  • 17
  • 99
  • 186
kramer65
  • 50,427
  • 120
  • 308
  • 488

1 Answers1

0

OK, found it. When using PWM, the program must be run as root.

halfer
  • 19,824
  • 17
  • 99
  • 186
kramer65
  • 50,427
  • 120
  • 308
  • 488
  • 1
    Yes, there's a comment to that effect in github.com/stianeikeland/go-rpio - it might be nice though if it remembered for you that when run as non-root, it used the "can't touch PWM" method and returned errors! :-) – torek Aug 23 '19 at 21:31