Skip to content
Snippets Groups Projects
Select Git revision
  • b7c5433eff78e5712236ddac84e16d9473fdb5b7
  • master default protected
2 results

C.mpg

Blame
  • main.py 2.19 KiB
    from machine import Pin, PWM, Timer
    import time
    
    # constants
    spike_duration = 100 # spike duration, ms
    pulse_duration = 1500 # dwell (including spike time), ms
    total_cycle = 3000  # 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
    i = 0.5 # counter increment, ms
    counter = -i # counter, ms
    duty = 0 # duty cycle, %
    duty_percent = 12.5
    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")