-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
85 lines (72 loc) · 2.16 KB
/
main.go
File metadata and controls
85 lines (72 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"machine"
"time"
)
const (
measureFrequency = time.Second * 60
moistureThreshold = 21000 // Higher moisture level means the soil is drier
)
var (
systemLed = machine.D13
// Plant pair 1
moistureSensor1 = machine.ADC{Pin: machine.ADC0}
pump1 = machine.D11
// Plant pair 2
moistureSensor2 = machine.ADC{Pin: machine.ADC1}
pump2 = machine.D10
)
func main() {
machine.InitADC() //! Better don't forget to initialize ADC
configureDigitalOutputPins(pump1, pump2)
configureAnalogInputPins(machine.ADCConfig{
Reference: 5000, // 5 Volts
Resolution: 10, // 10 bits
}, moistureSensor1, moistureSensor2)
// Check the moisture level in a certain interval
for {
controlPump(moistureSensor1, pump1)
controlPump(moistureSensor2, pump2)
time.Sleep(measureFrequency)
}
}
// configureDigitalOutputPins configures the given pins as digital output pins
func configureDigitalOutputPins(pins ...machine.Pin) {
for _, p := range pins {
p.Configure(machine.PinConfig{Mode: machine.PinOutput})
}
}
// configureAnalogInputPins configures the given pins as analog input pins with the given configuration
func configureAnalogInputPins(conf machine.ADCConfig, pins ...machine.ADC) {
for _, p := range pins {
p.Configure(conf)
}
}
// controlPump controls the pump based on the moisture level
func controlPump(sensor machine.ADC, pump machine.Pin) {
const wateringDuration = time.Millisecond * 1500
moisture := readMoisture(sensor)
println("Moisture level: ", moisture)
// If moisture level is dried, turn on the warning light
if moisture > moistureThreshold {
runPump(pump, wateringDuration)
} else {
blink(systemLed, time.Millisecond*250)
}
}
// readMoisture reads the moisture level from the given sensor and returns it
func readMoisture(sensor machine.ADC) uint16 {
return sensor.Get() // Analog value of moisture level
}
// runPump starts a pump for a certain duration
func runPump(pump machine.Pin, duration time.Duration) {
pump.High()
time.Sleep(duration)
pump.Low()
}
// blink blinks the given LED for the given duration
func blink(led machine.Pin, duration time.Duration) {
led.High()
time.Sleep(duration)
led.Low()
}