Newer
Older
from machine import Pin, PWM, Timer
import time
# constants
spike_duration = 3.5 # spike duration, ms
pulse_duration = 300 # dwell (including spike time), ms
total_cycle = 2000 # period of the cycle, ms
# establish pins
led_pin = Pin(27, Pin.OUT)
sol_pin = Pin(29, Pin.OUT)
# establish timer object
timer = Timer() # timer object
# initiate variables
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
86
87
88
89
90
91
92
93
94
hold_duty = round(duty_percent/100*65535) # reduced duty cycle, %
# pwm object, off
pwm_led = PWM(led_pin, freq=10000, duty_u16=duty)
pwm_sol = PWM(sol_pin, freq=100000, duty_u16=duty)
def pwm_control(timer):
global counter, duty
counter += i
if counter < spike_duration:
# spike pulse, 100% duty cycle
duty = 65535
elif counter < pulse_duration:
# hold, X% duty cycle
duty = hold_duty
elif counter < total_cycle:
# 0% duty cycle
duty = 0
else:
# counter rest
counter = -i;
print("reset counter")
pwm_led.duty_u16(duty) # set the duty cycle of the led
pwm_sol.duty_u16(duty) # set the duty cycle of the solenoid
print("initiate runtime")
try:
# timer initialize
timer.init(freq=(1/i)*1e3, mode=Timer.PERIODIC, callback=pwm_control)
# allocate for extra application functionality
while True:
pass
except KeyboardInterrupt:
# catch a soft reboot or keyboard interrupt
print("omg")
# turn off the dang pins! this for your own good
# (unless you want a burnt out solenoid)
finally:
print("purge")
# turn off the main timer
timer.deinit()
# set pwm duty cycle to 0, this way needs a delay before
# the pwm.deinit() call unfortunately
#pwm_led.duty_u16(0) # set the duty cycle of the led
#pwm_sol.duty_u16(0) # set the duty cycle of the solenoid
#time.sleep(0.1)
# turn off the pwm timers
pwm_led.deinit()
pwm_sol.deinit()
# reinitialize pins as digital outputs
led_pin.init(Pin.OUT)
sol_pin.init(Pin.OUT)
# set digital pins to 0
led_pin.value(0)
sol_pin.value(0)
print("purge complete")