github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/examples/pwm/pwm.go (about) 1 package main 2 3 // This example demonstrates some features of the PWM support. 4 5 import ( 6 "machine" 7 "time" 8 ) 9 10 const delayBetweenPeriods = time.Second * 5 11 12 func main() { 13 // Delay a bit on startup to easily catch the first messages. 14 time.Sleep(time.Second * 2) 15 16 // Configure the PWM with the given period. 17 err := pwm.Configure(machine.PWMConfig{ 18 Period: 16384e3, // 16.384ms 19 }) 20 if err != nil { 21 println("failed to configure PWM") 22 return 23 } 24 25 // The top value is the highest value that can be passed to PWMChannel.Set. 26 // It is usually an even number. 27 println("top:", pwm.Top()) 28 29 // Configure the two channels we'll use as outputs. 30 channelA, err := pwm.Channel(pinA) 31 if err != nil { 32 println("failed to configure channel A") 33 return 34 } 35 channelB, err := pwm.Channel(pinB) 36 if err != nil { 37 println("failed to configure channel B") 38 return 39 } 40 41 // Invert one of the channels to demonstrate output polarity. 42 pwm.SetInverting(channelB, true) 43 44 // Test out various frequencies below, including some edge cases. 45 46 println("running at 0% duty cycle") 47 pwm.Set(channelA, 0) 48 pwm.Set(channelB, 0) 49 time.Sleep(delayBetweenPeriods) 50 51 println("running at 1") 52 pwm.Set(channelA, 1) 53 pwm.Set(channelB, 1) 54 time.Sleep(delayBetweenPeriods) 55 56 println("running at 25% duty cycle") 57 pwm.Set(channelA, pwm.Top()/4) 58 pwm.Set(channelB, pwm.Top()/4) 59 time.Sleep(delayBetweenPeriods) 60 61 println("running at top-1") 62 pwm.Set(channelA, pwm.Top()-1) 63 pwm.Set(channelB, pwm.Top()-1) 64 time.Sleep(delayBetweenPeriods) 65 66 println("running at 100% duty cycle") 67 pwm.Set(channelA, pwm.Top()) 68 pwm.Set(channelB, pwm.Top()) 69 time.Sleep(delayBetweenPeriods) 70 71 for { 72 time.Sleep(time.Second) 73 } 74 }