Skip to content

Commit cef39c5

Browse files
committed
Automatic pin mode handling for dht driver example
1 parent 99ee974 commit cef39c5

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

examples/dht/main.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,12 @@ import (
44
"fmt"
55
"machine"
66
"time"
7+
78
"tinygo.org/x/drivers/dht"
89
)
910

1011
func main() {
11-
pin := machine.D6
12+
pin := &machinePin{pin: machine.D6}
1213
dhtSensor := dht.New(pin, dht.DHT11)
1314
for {
1415
temp, hum, err := dhtSensor.Measurements()

examples/dht/pin.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
//go:build baremetal && tinygo
2+
3+
package main
4+
5+
import (
6+
"machine"
7+
)
8+
9+
// machinePin wraps machine.Pin to ensure correct pin mode is set when Get or Set methods are called.
10+
11+
type machinePin struct {
12+
pin machine.Pin
13+
mode machine.PinMode
14+
modeSet bool
15+
}
16+
17+
func (p *machinePin) Get() bool {
18+
if !p.modeSet || p.mode != machine.PinInput {
19+
p.pin.Configure(machine.PinConfig{Mode: machine.PinInput})
20+
p.mode = machine.PinInput
21+
}
22+
return p.pin.Get()
23+
}
24+
25+
func (p *machinePin) Set(high bool) {
26+
if !p.modeSet || p.mode != machine.PinOutput {
27+
p.pin.Configure(machine.PinConfig{Mode: machine.PinOutput})
28+
p.mode = machine.PinOutput
29+
}
30+
p.pin.Set(high)
31+
}

0 commit comments

Comments
 (0)