dongsuiying7773 2019-08-23 19:36
浏览 181

像我在Python中一样,如何在Go中控制Raspi上的PWM引脚?

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.

Does anybody know what I'm missing here? Any tips would be welcome!

  • 写回答

1条回答 默认 最新

  • dongzhang3482 2019-08-23 19:53
    关注

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

    I wish you all a beautiful day!

    评论

报告相同问题?

悬赏问题

  • ¥15 flask项目,怎么使用AJAX传数据库数据到echarts图表的data里,实现异步加载数据。
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?