Created
February 17, 2021 21:42
-
-
Save hamid-elaosta/3854d0e586fec4973b4b0f6241bafe0e to your computer and use it in GitHub Desktop.
Quick and Dirty Pi PWM Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Quick and Dirty PWM tool in Golang to pulse Pin 18 (PWM) on Raspberry PI at a set frequency, and duty cycle | |
| // Usage: ./pwm <frequency> <duty> <period> | |
| // e.g. For 32kHz with a duty cycle of 1/4: | |
| // sudo ./pwm 32000 1 4 | |
| // Must run as root for now, I haven't had time to write a udev rule for /dev/mem | |
| package main | |
| import ( | |
| "fmt" | |
| "log" | |
| "os" | |
| "strconv" | |
| "time" | |
| "github.com/stianeikeland/go-rpio/v4" | |
| ) | |
| func main() { | |
| fmt.Println("parse args") | |
| args := os.Args | |
| if len(args) < 4 { | |
| fmt.Printf("usage: %s <freq> <duty> <period>\n", args[0]) | |
| os.Exit(1) | |
| } | |
| fmt.Println("open memory") | |
| err := rpio.Open() | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| defer rpio.Close() | |
| fmt.Println("select pin 18") | |
| pin := rpio.Pin(18) | |
| fmt.Println("set pin mode to pwm") | |
| pin.Mode(rpio.Pwm) | |
| frq, err := strconv.ParseInt(args[1], 10, 64) | |
| if err != nil { | |
| fmt.Printf("failed to parse frequency value: %q\n", args[0]) | |
| } | |
| duty, err := strconv.ParseUint(args[2], 10, 32) | |
| if err != nil { | |
| fmt.Printf("failed to parse duty length value: %q\n", args[0]) | |
| } | |
| period, err := strconv.ParseUint(args[3], 10, 32) | |
| if err != nil { | |
| fmt.Printf("failed to parse period value: %q\n", args[0]) | |
| } | |
| fmt.Printf("set frequency to %d\n", int(frq)) | |
| pin.Freq(int(frq)) | |
| fmt.Printf("set duty cycle to %d/%d\n", uint32(duty), uint32(period)) | |
| pin.DutyCycle(uint32(duty), uint32(period)) | |
| for { | |
| time.Sleep(time.Second) | |
| fmt.Print(".") | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output is pretty accurate ~32kHz and ~3.3V