def gps(): new_data = False # Callback Function def pps_callback(line): global new_data # Use Global to trigger update new_data = True # Instantiate the micropyGPS object my_gps = MicropyGPS() # Setup the connection to your GPS here # This example uses UART 3 with RX on pin Y10 # Baudrate is 9600bps, with the standard 8 bits, 1 stop bit, no parity # Also made the buffer size very large (1000 chars) to accommodate all the characters that stack up # each second uart = pyb.UART(sys_config['pmod']['p3']['uart'], 9600, read_buf_len=1000) # Release Reset reset = pyb.Pin(sys_config['pmod']['p3']['reset'], pyb.Pin.OUT_PP) reset.high() # Create an external interrupt on pin X8 pps_pin = pyb.Pin(sys_config['pmod']['p3']['one_pps'], pyb.Pin.IN, pull=pyb.Pin.PULL_UP) extint = pyb.ExtInt(pps_pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, pps_callback) # Main Infinite Loop while 1: # Do Other Stuff Here....... # Update the GPS Object when flag is tripped if new_data: while uart.any(): my_gps.update( chr(uart.readchar()) ) # Note the conversion to to chr, UART outputs ints normally #print('UTC Timestamp:', my_gps.timestamp) print('Date:', my_gps.date_string('long')) print('Latitude:', my_gps.latitude_string()) print('Longitude:', my_gps.longitude_string()) print('Horizontal Dilution of Precision:', my_gps.hdop) print('Satellites in use:', my_gps.satellites_in_use) print() new_data = False # Clear the flag
def main(): print("RGBC Test") print("=========") exti = pyb.ExtInt(x11, mode=pyb.ExtInt.IRQ_FALLING, pull=pyb.Pin.PULL_NONE, callback=None) exti = pyb.ExtInt(x11, mode=pyb.ExtInt.IRQ_FALLING, pull=pyb.Pin.PULL_NONE, callback=cb) iclear() apds.enableLightSensor() apds.setAmbientLightIntEnable(0) apds.setProxIntHighThresh(200) apds.setProxIntLowThresh(0x0) apds.enableProximitySensor() while True: sleep(0.25) r = apds.readRedLight() g = apds.readGreenLight() b = apds.readBlueLight() c = apds.readAmbientLight() p = apds.readProximity() print('%5d %5d %5d %5d %8d %d' % (r, g, b, c, p, x11()))
def interrupt_setAB(self): self.interrupt_disable() self.ml1_interrupt = pyb.ExtInt(self.MortorA_C1, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_NONE, self.mlc1_in_callback) self.ml2_interrupt = pyb.ExtInt(self.MortorA_C2, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_NONE, self.mlc2_in_callback) self.mr1_interrupt = pyb.ExtInt(self.MortorB_C1, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_NONE, self.mrc1_in_callback) self.mr2_interrupt = pyb.ExtInt(self.MortorB_C2, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_NONE, self.mrc2_in_callback)
def __init__(self): # set up motor with PWM and timer control self.A1 = Pin('X3', Pin.OUT_PP) # A is right motor self.A2 = Pin('X4', Pin.OUT_PP) self.B1 = Pin('X7', Pin.OUT_PP) # B is left motor self.B2 = Pin('X8', Pin.OUT_PP) self.PWMA = Pin('X1') self.PWMB = Pin('X2') self.speed = 0 # +100 full speed forward, -100 full speed back self.turn = 0 # turn is +/-100; 0 = left/right same speed, # ... +50 = left at speed, right stop, +100 = right back full # Configure counter 2 to produce 1kHz clock signal self.tim = Timer(2, freq=1000) # Configure timer to provide PWM signal self.motorA = self.tim.channel(1, Timer.PWM, pin=self.PWMA) self.motorB = self.tim.channel(2, Timer.PWM, pin=self.PWMB) self.lsf = 0 # left motor speed factor +/- 1 self.rsf = 0 # right motor speed factor +/- 1 self.countA = 0 # speed pulse count for motorA self.countB = 0 # speed pulse count for motorB self.speedA = 0 # actual speed of motorA self.speedB = 0 # actual speed of motorB # Create external interrupts for motorA and motorB Hall Effect Senors self.motorA_int = pyb.ExtInt('Y4', pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_NONE, self.isr_motorA) self.motorB_int = pyb.ExtInt('Y6', pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_NONE, self.isr_motorB) self.speed_timer = pyb.Timer(8, freq=10) self.speed_timer.callback(self.isr_speed_timer)
def __init__(self, pin_x, pin_y, reverse, scale): self.reverse = reverse self.scale = scale self.forward = True self.pin_x = pin_x self.pin_y = pin_y self._pos = 0 self.x_interrupt = pyb.ExtInt(pin_x, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_NONE, self.x_callback) self.y_interrupt = pyb.ExtInt(pin_y, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_NONE, self.y_callback)
def pinSetup(self): # print("PinSetup") microSwitch_in = 'X1' disableSleep_button = 'X2' self.p_disableSleep_button = (disableSleep_button, pyb.Pin.IN, pyb.Pin.PULL_DOWN) self.p_in = pyb.Pin(microSwitch_in, pyb.Pin.IN, pyb.Pin.PULL_DOWN) self.p_disableSleep_button = pyb.Pin(disableSleep_button, pyb.Pin.IN, pyb.Pin.PULL_DOWN) # print(self.p_in) # print(self.p_in.value()) self.myExtInt_disableSleep = pyb.ExtInt(pyb.Pin('X2'),pyb.ExtInt.IRQ_RISING,pyb.Pin.PULL_DOWN, self.microSwitch_callback) self.myExtIntMicroswitch = pyb.ExtInt(pyb.Pin('X1'),pyb.ExtInt.IRQ_FALLING,pyb.Pin.PULL_DOWN, self.disableSleep_callback) print("after enable_irq()")
def __init__(self, _pinA, _pinB): #print('init encoderTask') self.count = 0 self.errors = 0 self.prevA = 0 self.prevB = 0 self.pinA = _pinA self.pinB = _pinB self.intA = pyb.ExtInt(_pinA, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_UP, self.runInt) self.intB = pyb.ExtInt(_pinB, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_UP, self.runInt)
def __init__(self, Apin='X21', Bpin='X22'): self.B = pyb.Pin(Bpin) self.A = pyb.Pin(Apin) self.prevA = self.A.value() self.prevB = self.B.value() self.CWcount = 0 self.CCWcount = 0 self.position = 0 self.Bint = pyb.ExtInt(self.B, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_UP, self.callback) self.Aint = pyb.ExtInt(self.A, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_UP, self.callback)
def enable_interrupt(button, interrupt, on_press=True, on_release=False): """Attaches an interrupt to a button on_press defines whether it should be called when the button is pressed on_release defines whether it should be called when the button is releaseed The callback function must accept exactly 1 argument, which is the line that triggered the interrupt. """ global _tilda_interrupts pin = _get_pin(button) if button in _tilda_interrupts: # If someone tries to set an interrupt on a pin that already # has one that's totally ok, but we need to remove the old one # first disable_interrupt(button) if not (on_press or on_release): return mode = None if on_press and on_release: mode = pyb.ExtInt.IRQ_RISING_FALLING else: if pin.pull() == pyb.Pin.PULL_DOWN: mode = pyb.ExtInt.IRQ_RISING if on_press else pyb.ExtInt.IRQ_FALLING else: mode = pyb.ExtInt.IRQ_FALLING if on_press else pyb.ExtInt.IRQ_RISING _tilda_interrupts[button] = { "interrupt": pyb.ExtInt(pin, mode, pin.pull(), interrupt), "mode": mode, "pin": pin }
def start(self): """ Try and create an external interrupt for the supplied Pin. If successful your 'callback' will be called every time the PIR sensor detects a movement. :return: bool, error_message """ return_value = True error_message = None try: self._pir_interrupt = pyb.ExtInt(self.pir_pin, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_UP, self.pir_callback) except ValueError as error: print(error.args[0]) if error.args[0] == "ExtInt vector {0} is already in use".format(self._pir_interrupt.line()): self._pir_interrupt.enable() return return_value, "PIR is now enabled" else: print("ValueError: {0}".format(error)) return_value = False error_message = error except OSError as error: print("OS Error: {0}".format(error)) return_value = False error_message = error except: print("Unexpected error!") raise return return_value, error_message
def int_external(): global source, event, ctr ahb1enr[0] = 1 # Port A clock pa_moder[PA_OUT] = 1 # Output pa_odr[PA_OUT] = 1 # Drives ExtInt high print("Before setup...") dump(regs_ext_int) ext_int = pyb.ExtInt(pyb.Pin("Y1"), pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, callback_ext_int) print("After setup...") dump(regs_ext_int) while True: new_state = input("Ext Int pin state (0/1)? ") if not new_state: break if new_state in ("0", "1"): pa_odr[PA_OUT] = int(new_state) print("{}: Event {}, Count = {}".format(source, event, ctr)) print() print("After usage...") dump(regs_ext_int) ext_int.disable() print() print("After disabling interrupt...") dump(regs_ext_int) pa_odr[PA_OUT] = 0 # Drives ExtInt low
def init_interrupts(self): """Initializes all external interrupts to wakes up board from sleep mode.""" for pin in self.config["Irq_Pins"]: self.irqs.append( pyb.ExtInt(pyb.Pin(pin[0], pyb.Pin.IN), eval("pyb.ExtInt." + pin[1]), eval("pyb.Pin." + pin[2]), self.ext_callback))
def main(): print("RGBC Test") print("=========") #exti = pyb.ExtInt(x11, mode=pyb.ExtInt.IRQ_FALLING, pull=pyb.Pin.PULL_NONE, callback=None) exti = pyb.ExtInt(x11, mode=pyb.ExtInt.IRQ_FALLING, pull=pyb.Pin.PULL_NONE, callback=cb) iclear() apds.enableLightSensor() apds.setAmbientLightIntEnable(0) apds.setProxIntHighThresh(200) apds.setProxIntLowThresh(0x0) apds.enableProximitySensor() while True: # sleep(0.25) # r = apds.readRedLight() # g = apds.readGreenLight() # b = apds.readBlueLight() # c = apds.readAmbientLight() # p = apds.readProximity() # print('Red: %5d Green: %5d Blue: %5d Ambient: %5d proximity: %8d interrupt: %d' % (r, g, b, c, p, x11())) sensor = ColorSensor() r, g, b = sensor.measure() draw_screen(r, g, b)
def main(self): """ Main function where interrupt handler is initialized and a callback function passed :param: None :return: None """ # Allocate exception buffer since heap cannot be allocated within an ISR context micropython.alloc_emergency_exception_buf(100) # Set up interrupt handler ext_int = pyb.ExtInt(self.pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_NONE, self.measure) while self.num_seconds < (self.max_duration // self.sample_period): # Sleep for specified interval to count number of interrupts received time.sleep(self.sample_period) # Disable IRQs and process result pyb.disable_irq() rpm = self.irq_count * 60 / (2 * self.blades) output_str = str(self.num_seconds) + "," + "{0:.2f}".format(rpm) # Print the result to serial console print(output_str) # Reset IRQ counter for the next interval self.irq_count = 0 self.num_seconds += self.sample_period # Enable IRQs pyb.enable_irq()
def test_11(self): flagOk=False try: int = pyb.ExtInt(None,pyb.ExtInt.IRQ_RISING,pyb.Pin.PULL_NONE,self.callbackTest) flagOk=True except: pass self.assertEqual(flagOk,False,"Interrupt. Invalid Pin obj")
def __init__(self, pin, mode, pull, customcallback = None, timeout = None): super().__init__() self.customcallback = customcallback if timeout is None: self.forever = True else: self.setdelay(timeout) self.irq = pyb.ExtInt(pin, mode, pull, self.intcallback)
def test_12(self): flagOk=False try: int = pyb.ExtInt(Self.p8,99,pyb.Pin.PULL_NONE,self.callbackTest) flagOk=True except: pass self.assertEqual(flagOk,False,"Interrupt. Invalid edge")
def disable_interrupt(button): global _tilda_interrupts if button in _tilda_interrupts: interrupt = _tilda_interrupts[button] pyb.ExtInt(interrupt["pin"], interrupt["mode"], interrupt["pin"].pull(), None) del _tilda_interrupts[button] init([button])
def test_13(self): flagOk=False try: int = pyb.ExtInt(Self.p8,pyb.ExtInt.IRQ_RISING,99,self.callbackTest) flagOk=True except: pass self.assertEqual(flagOk,False,"Interrupt. Invalid pull")
def interrupt(self, func): self._interrupt = None self._func = func if (func != None): self._interrupt = pyb.ExtInt(self._trigger, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_DOWN, self._inthandler) self._inton = True
def enableInterrupt(self): # + try: # GPIO.add_event_detect(self.irq, GPIO.RISING, callback=self.handleInterrupt) self.irq = pyb.ExtInt('X2', pyb.ExtInt.IRQ_RISING, callback=self.handleInterrupt, pull=pyb.Pin.PULL_DOWN) except: print('Error IQR')
def initGPIO(): global pinPIR global pinPowerSwitch pinPIR = pyb.ExtInt("P3", pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, callback=handlePIR) pinPowerSwitch = pyb.Pin("P6", pyb.Pin.OUT_PP)
def pinSetup(self): print("PinSetup") microSwitch_in = 'X1' self.p_in = machine.Pin(microSwitch_in, machine.Pin.IN, pyb.Pin.PULL_DOWN) print(self.p_in) print(self.p_in.value()) self.myExtInt = pyb.ExtInt(pyb.Pin('X1'), pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, self.callback) print("after enable_irq()")
def enable_interrupts(self): self.write_register('INTCON', 0) # Set all interupts to IRQ_RISING_FALLING mode. self.write_register('DEFVAL', 0) # Set default compare value to low. self.write_bit('IOCON', 1, True, n_bytes=1) # Set interrupt pin active high. self.write_bit('IOCON', 6, True, n_bytes=1) # Set port A, B interrupt pins to mirror. self.extint = pyb.ExtInt(self.interrupt_pin, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_NONE, self.ISR) self.pin_callbacks = {} # Dictionary of {pin: callback} self.interrupts_enabled = True
def run(self): global last_up, last_down, last_saved, temp_changed, state, pid last_up = pyb.millis() last_down = last_up last_saved = last_up temp_changed = False restore_settings() pid = PIDController(set_temp=state['set_temp']) pyb.ExtInt(self.up_pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_DOWN, adjust_set_up) pyb.ExtInt(self.down_pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_DOWN, adjust_set_down) while True: state = self._update_devices_info() state = self.controller(state) pid.update(state['boiler_temp']) primitives = self.view(state) with self.display: self._draw(primitives)
def __init__(self, pin, mode, pull, customcallback=None, timeout=None): super().__init__() if not Pinblock.initialised: import pyb import micropython micropython.alloc_emergency_exception_buf(100) Pinblock.initialised = True self.customcallback = customcallback if timeout is None: self.forever = True else: self.setdelay(timeout) self.irq = pyb.ExtInt(pin, mode, pull, self.intcallback) # Porting: needs adaptation
def test_10(self): self.__writeSetup() int = pyb.ExtInt(self.p8,pyb.ExtInt.IRQ_RISING,pyb.Pin.PULL_NONE,self.callbackTest) int.disable() pyb.delay(10) self.p7.low() int.enable() # generate interrupt TestGPIO.flagInCallback=False self.p7.high() pyb.delay(10) self.assertEqual(TestGPIO.flagInCallback,True,"Rising edge interrupt")
def reaction_time(): # Record time called global _start_time _start_time = time.ticks_ms() _led.on() # Setup SW input as external interrupt global _ext_int if _ext_int is None: pin = machine.Pin('SW', machine.Pin.IN, machine.Pin.PULL_UP) _ext_int = pyb.ExtInt( pin, pyb.ExtInt.IRQ_FALLING, machine.Pin.PULL_UP, _cb ) else: _ext_int.enable()
def __init__(self, pins_dict, timer=6, reverse_pols=False): self.__enable = pwm.PWM(pins_dict['enable']) self.__control0 = pins_dict[ 'control0'] if not reverse_pols else pins_dict['control1'] self.__control0.init(pyb.Pin.OUT_PP) self.__control0.low() self.__control1 = pins_dict[ 'control1'] if not reverse_pols else pins_dict['control0'] self.__control1.init(pyb.Pin.OUT_PP) self.__control1.low() self.__led = pins_dict['led'] self.__led.init(pyb.Pin.OUT_PP) self.__tack0 = pins_dict['tack0'] if not reverse_pols else pins_dict[ 'tack1'] self.__tack1 = pins_dict['tack1'] if not reverse_pols else pins_dict[ 'tack0'] self.__tack1.init(pyb.Pin.IN) #pyb.millis doesn't have enough resolution #start timer at TIMER_FREQ, with max possible period if timer in [1, 8, 9, 10, 11]: self.__ucounter = pyb.Timer(timer, prescaler=int(pyb.freq()[3] / TIMER_FREQ), period=0x7fffffff) elif timer in [2, 3, 4, 5, 6, 7, 12, 13, 14]: self.__ucounter = pyb.Timer(timer, prescaler=int(pyb.freq()[2] / TIMER_FREQ), period=0x7fffffff) self.__tim_rollover = False #set a callback on the timer which sets __tim_rollover true if it overflows #i.e. it counts past it's period, without a tack occuring. #if so we assume speed is zero as we can no longer measure it self.__ucounter.callback(self.__ISR_TIMER_SPEED) self.__pulsetime = 0 #this is measured speed ... we are at rest self.__pulsedir = 0 #at init doesn't matter what direction this indicates #register interrupt on tack0 self.__extint = pyb.ExtInt(self.__tack0, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_UP, self.__ISR_TACK_SPEED)
def __init__(self, communication, dev_selector, reset_pin, dio_pin, verbose=True, do_calibration=True, calibration_freq=868): """ Init the object Send the device to sleep and do the calibration (if do_calibration=True) :param verbose: Set the verbosity True/False :param calibration_freq: call rx_chain_calibration with this parameter. Default is 868 :param do_calibration: Call rx_chain_calibration, default is True. """ self.DEBUG = verbose super().__init__(communication, dev_selector, addr_size=self.ADDR_MODE_8, msb_first=self.TRANSFER_MSB_FIRST) self.__dio = dio_pin self.__reset_pin = reset_pin self.reset() self.exists() self.__mode_mask = 0x87 # # set the callbacks for DIO0..3 IRQs. DIO4/5 are not supported # for pin, fun in zip(dio_pin, [self._dio0, self._dio1, self._dio2, self._dio3]): pyb.ExtInt(pin, pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_UP, callback=fun) # set mode to sleep self.set_mode(MODE.SLEEP) # more setup work: if do_calibration: self.rx_chain_calibration(calibration_freq) # set the dio_ mapping by calling the two get_dio_mapping_* functions self.get_dio_mapping_1() self.get_dio_mapping_2()