python - 如何像在 Python 中那样在 Go 中控制 Raspi 上的 PWM 引脚?

标签 python go raspberry-pi gpio pwm

我有一个 Raspberry Pi 3B,我想使用它来控制电机 PWM .在 Python 中,这非常适合将 GPIO 引脚的电压从 0% 逐渐增加到 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

由于我是用 Go 编写程序,所以我现在想在 Go 中做同样的事情(或类似的事情)。所以这就是我的尝试。

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)
}

an example of using go-rpio to control PWM here .该示例旨在控制 LED 而不是电机,但我想代码应该非常相似(如果不相同的话)。该示例使用了不同的值,因此我对这些值进行了一些改动,但没有结果。

我在这里错过了什么?

最佳答案

好的,找到了。使用 PWM 时,程序必须以 root 身份运行。

关于python - 如何像在 Python 中那样在 Go 中控制 Raspi 上的 PWM 引脚?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57632096/

相关文章:

arrays - 将多个返回函数分配给容器(列表)

http - 通过原始TCP套接字接受和路由HTTP请求

android - 在 appengine 或 android 上,我在哪里可以获得应用内计费 v3 api 的 token ?

c - 从Linux内核模块访问/dev/mem

c - 与 RPi 的 RS-232 通信

python - 增加计数器并在超过阈值时触发操作

python - Django 和枕头

python - 捕获异常并继续 Python 中的 try block

python - 如何自定义mongo查询比较规则

linux - Raspbian 上的 incron 无法正常工作