def demo_sleep_mode(): ''' Demonstrates putting the XBee into sleep mode. This is NOT sleep in the creating-a-delay-in-the-time.sleep()-sense; it instead puts the XBee into low-power mode. Note that if ATSM != 0, you'll get an "EALREADY" OSError exception. https://www.digi.com/resources/documentation/digidocs/90002219/#reference/r_sleep_mp.htm ''' from machine import Pin import time import xbee led = Pin("D5", Pin.OUT, value=0) xb = xbee.XBee() while True: # Blink at 5 Hz for 5 seconds. for _ in range(50): time.sleep_ms(100) led.toggle() # Start sleep mode. SLEEPTIME_ms = 60000 # Sleep for 1 minute. xb.sleep_now(SLEEPTIME_ms, pin_wake=False)
async def main(proto): # Test uses a 38KHz carrier. if ESP32: # Pins for IR LED gate pin = Pin(23, Pin.OUT, value=0) elif RP2: pin = Pin(17, Pin.OUT, value=0) else: pin = Pin('X1') classes = (NEC, SONY_12, SONY_15, SONY_20, RC5, RC6_M0) irb = classes[proto](pin, 38000) # My decoder chip is 38KHz # Uncomment the following to print transmit timing # irb.timeit = True b = [] # Rbutton instances px3 = Pin('X3', Pin.IN, Pin.PULL_UP) if PYBOARD else Pin( 18, Pin.IN, Pin.PULL_UP) px4 = Pin('X4', Pin.IN, Pin.PULL_UP) if PYBOARD else Pin( 19, Pin.IN, Pin.PULL_UP) b.append(Rbutton(irb, px3, 0x1, 0x7, proto)) b.append(Rbutton(irb, px4, 0x10, 0xb, proto)) if ESP32: while True: print('Running') await asyncio.sleep(5) elif RP2: led = Pin(25, Pin.OUT) while True: await asyncio.sleep_ms(500) # Obligatory flashing LED. led(not led()) else: led = LED(1) while True: await asyncio.sleep_ms(500) # Obligatory flashing LED. led.toggle()
class Scale: """ A Class to represent SparkFun's HX711 Scale """ @staticmethod def twosbinarystring_to_integer(value_string, bits): """ Given a binary string of a number in 2's complement, compute the integer value """ value = int(value_string, 2) if value & (1 << (bits - 1)) != 0: value = value - (1 << bits) return value def __init__(self, gain=1, data_cycles=24, clock_pin="G16", data_pin="G15"): self.gain = gain self.data_cycles = data_cycles self.clock_pin = clock_pin self.data_pin = data_pin self.clk = Pin(self.clock_pin, mode=Pin.OUT) self.clk.mode(Pin.OUT) self.data = Pin(self.data_pin, mode=Pin.IN, pull=Pin.PULL_DOWN) self.data.mode(Pin.IN) def read(self): self.clk.value(0) wait_iterations = 0 while wait_iterations < 100 and self.data.value() != 0: wait_iterations += 1 sleep_ms(1) if wait_iterations >= 100: raise Exception("ADC Communication Failure") # Retrieve ADC Reading observation = [] for i in range(self.data_cycles): self.clk.toggle() self.clk.toggle() observation.append(self.data.value()) # Set ADC Gain for next reading for i in range(self.gain): self.clk.toggle() self.clk.toggle() ob_string = ''.join([str(i) for i in observation]) ob_value = self.twosbinarystring_to_integer(ob_string, bits=self.data_cycles) return ob_value
class Heartbeat: def __init__(self): self.count = 0 self.led = Pin('P9', mode=Pin.OUT) def run(self): if self.count < 0: self.count = 20 self.led.toggle() self.count -= 1
def main(): # set up LED led = Pin(25, Pin.OUT) # turn on LED led.toggle() # create notes and save in flash create_notes() # create I2S object audio_out = I2S( 0, # I2S ID sck=Pin(0), # SCK Pin ws=Pin(1), # WS Pin sd=Pin(2), # SD Pin mode=I2S.TX, # I2S transmitter bits=16, # 16 bits per sample format=I2S.MONO, # Mino - single channel rate=SR, # sample rate ibuf=2000, # I2S buffer length ) # set up btns btns = [ Pin(3, Pin.IN, Pin.PULL_UP), Pin(4, Pin.IN, Pin.PULL_UP), Pin(5, Pin.IN, Pin.PULL_UP), Pin(6, Pin.IN, Pin.PULL_UP), Pin(7, Pin.IN, Pin.PULL_UP) ] # "ready" note play_note(('C4', 262), audio_out) print("Piano ready!") # turn off LED led.toggle() while True: for i in range(5): if btns[i].value() == 0: play_note(btnNotes[i], audio_out) break time.sleep(0.2)
def demo_prohibit_sleep(): ''' Prevent the XBee from going into sleep mode using the wake_lock Good for protecting critical sections of MicroPython code. https://www.digi.com/resources/documentation/digidocs/90002219/#reference/r_sleep_at_cmds.htm ''' print("Starting prohibit sleep demo.") from machine import Pin import time import xbee led = Pin("D5", Pin.OUT, value=0) xb = xbee.XBee() with xb.wake_lock: # Ensure that we cannot be interrupted with sleep in the middle of this. while True: time.sleep_ms(100) led.toggle()
def demo_handle_api_frames(): ''' Provides loopback functionality. Receives a User Data Relay API frame from the serial interface, adds some data to it, then sends it back to the sender. How to run this demo: 1) In XCTU's MicroPython Terminal, first put the XBee into MicroPython mode (+++-wait-ATAP4). Then press Ctrl+f, paste in the code, and compile it into /flash/main.mpy. Then press Ctrl+d to soft reboot and run the code. (Make sure there is no /flash/main.py file or that would get executed instead.) Alternatively, copy this code into /flash/main.py using XCTU's File System Manager tool (and then you can press the reset pushbutton to restart the system and run the new code). Then put the device back into API Mode with Escapes (+++-wait-ATAP2) so that it is ready to receive the data. Close the serial port in XCTU when done so that you can reopen the port with gecko.py. 2) In another terminal, run api_frames_loopback_test() defined in gecko.py. That script will open the serial port using PySerial and send a User Data Relay message to MicroPython. The code below receives that message, appends to it, and then sends it back to the sender. Notes: - You could add the "+++-wait-ATAP4" commands here to streamline changing modes for testing. - You can also set up a loopback example within MicroPython. relay.send(relay.MICROPYTHON, b"blah") and then call relay.receive(). ''' print("Launching API frames demo.") from machine import Pin import time from xbee import relay led = Pin( "D5", Pin.OUT, value=0 ) # DIO5 = XBee3 Cellular "Associated Indicator" LED, which is Pin 15 of the through-hole package. while True: rx = relay.receive() if rx is not None: dest = rx['sender'] data = rx['message'] + b'world' relay.send(dest, data) time.sleep_ms(500) led.toggle()
def demo_blink_LED(): ''' Demonstrates toggling a GPIO pin to drive an LED. ''' from machine import Pin import time led = Pin( "D5", Pin.OUT, value=0 ) # DIO5 = XBee3 Cellular "Associated Indicator" LED, which is Pin 15 of the through-hole package. for _ in range(10): time.sleep_ms(100) led.toggle() led.value(1) time.sleep_ms(2000) while True: time.sleep_ms(100) led.toggle()
class Trigger_Monitor(object): ''' Is there a way to change the callback? ''' def __init__(self): # OUTPUT/INPUT self.pins = ['GP16', 'GP13'] self.outputPin = Pin(self.pins[0], mode=Pin.OUT, value=1) self.inputPin = Pin(self.pins[1], mode=Pin.IN, pull=Pin.PULL_UP) self.triggerCount = 0 self._triggerType_ = Pin.IRQ_RISING self.inputIRQ = self.inputPin.irq(trigger=self._triggerType_, handler=self.pinHandler) self.irqState = True def toggleInput(self, time_ms = 5): self.outputPin.toggle() time.sleep_ms(time_ms) def pinHandler(self, pin_o): # global self.pin_irq_count_trigger # global self.pin_irq_count_total # self._triggerType_ # if self._triggerType_ & self.inputIRQ.flags(): # self.pin_irq_count_trigger += 1 self.triggerCount += 1 def getTriggerCount(self): print("Trigger Count: ", self.triggerCount) def resetTriggerCount(self): self.triggerCount = 0 def disableIRQ(self): self.irqState = machine.disable_irq() # Start of critical section def reEnableIRQ(self): machine.enable_irq(True) self.irqState=True
class Doorbell: _frame = [ 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1 ] # (short_pulse_duration, long_pulse_duration) _pulse_timings = (475, 1435) _frame_spacing = 8667 def __init__(self, pin): self.pin = Pin(pin, Pin.OUT) def send_frame(self): for f in self._frame: self.pin.toggle() sleep_us(self._pulse_timings[f]) self.pin.value(0) def ring(self, times): for i in range(times): self.send_frame() sleep_us(self._frame_spacing)
class Pico(object): def __init__(self): self.led_pini = Pin(25, Pin.OUT) self.zamanlayici = Timer() def sicaklik_sensoru_ayarla(self): self.sicaklik_sensoru = ADC(4) def zamanlayiciyi_ayarla(self, frekans, mod, cb): self.zamanlayici.init(freq=frekans, mode=mod, callback=cb) def zamanlayiciyi_durdur(self): self.zamanlayici.deinit() def led_yaksöndür(self, zamanlayici): self.led_pini.toggle() def celcius_oku(self): #Referans: #https://github.com/raspberrypi/pico-micropython-examples/blob/master/adc/temperature.py ham_deger = self.sicaklik_sensoru.read_u16() * 3.3 / (65535) return 27 - (ham_deger - 0.706) / 0.001721
def main(): # set internal clock rtc = settime(timezone_offset=TIMEZONE_OFFSET) year, month, day, hour, minute, second, *_ = rtc.now() trigger = Pin('GP5', mode=Pin.OUT) trigger.value(0) # initial trigger timer timer = Timer(3, mode=Timer.PERIODIC, width=32) timer_channel = timer.channel(Timer.A | Timer.B, period=30000000) timer_channel.irq(handler=lambda t: trigger.toggle(), trigger=Timer.TIMEOUT) try: while True: leds = clock2matrix(hour=hour, minute=minute).columns # led matrix multiplexing current_trigger = trigger.value() while trigger.value() == current_trigger: for col in leds: latch.value(0) # write current time spi.write(col) # update LEDs latch.value(1) sleep_ms(1) latch.value(0) spi.write(OFF) latch.value(1) sleep_us(50) latch.value(0) spi.write(OFF) latch.value(1) year, month, day, hour, minute, second, *_ = rtc.now() # update rtc at 04:00 if hour == 4 and minute == 0: rtc = settime(timezone_offset=TIMEZONE_OFFSET) except Exception as e: matrix_off() while True: print(e) sleep_ms(2000)
# Toggle LED command. DR_CMD_TOGGLE = "TOGGLE LED" # Toggle LED answer. DR_ANSWER_TOGGLE = "LED TOGGLED" # Unknown command answer. DR_ANSWER_UNKNOWN = "UNKNOWN COMMAND" print(" +---------------------------------------------+") print(" | XBee MicroPython Read Device Request Sample |") print(" +---------------------------------------------+\n") # Set up the LED pin object to manage the LED status. Configure the pin # as output and set its initial value to off (0). led_pin = Pin(LED_PIN_ID, Pin.OUT, value=0) # Start reading device requests. while True: request = cloud.device_request_receive() if request is not None: # A device request has been received, process it. data = request.read() if data.decode("utf-8").strip() == DR_CMD_TOGGLE: print("- Toggle LED device request received.") led_pin.toggle() written = request.write(bytes(DR_ANSWER_TOGGLE, "utf-8")) else: written = request.write(bytes(DR_ANSWER_UNKNOWN, "utf-8")) request.close() time.sleep(5)
from machine import Pin import utime relay1 = Pin(2, Pin.OUT) relay2 = Pin(3, Pin.OUT) relay3 = Pin(4, Pin.OUT) relay4 = Pin(5, Pin.OUT) while True: relay1.toggle() utime.sleep(0.5) relay2.toggle() utime.sleep(0.5) relay3.toggle() utime.sleep(0.5) relay4.toggle() utime.sleep(0.5) relay1(1) utime.sleep(0.5) relay1(0) utime.sleep(0.5)
from machine import Timer, Pin, HeartBeat #disable heartbeat #per - https://micropython.org/resources/docs/en/latest/wipy/library/machine.html HeartBeat().disable() #turn LED on # (says v1.6, led works/HB is incorrect?) https://micropython.org/resources/docs/en/latest/wipy/wipy/tutorial/repl.html#linux led = Pin('GP25', mode=Pin.OUT) led(1) #simple function to blink lamp blink = lambda f:led.toggle() #Much of 1.4.6 doc is just bad/does not match actual v1.4.6 WiPy firmware #https://github.com/micropython/micropython/blob/v1.4.6/docs/pyboard/tutorial/timer.rst #initialize a timer tim = Timer(4) #1-14 exist; 3 is for internal use; avoid 5+6 (used for servo control or ADC/DAC) tim.init(mode=Timer.PERIODIC) #configure a timer 'channel' tim_a = tim.channel( tim.A, freq=5) #less than 5per sec did not work #add something useful to the running channel tim_a.irq(handler=blink) #blinks strangely rapidly #disable the timer 'channel' tim_a = None #still blinking #tim.deinit() #stopped, terminal froze. tim.channel( tim.A, freq=5) #stopped blinking
def tick(timer): led = Pin(25, Pin.OUT) led.toggle()
# main.py -- put your code here! from machine import Pin import time led = Pin("GP16", Pin.OUT) led.toggle() def log(msg): print(msg) def btnPressed(pin): led.toggle() time.sleep_us(100) btn = Pin("GP17", Pin.IN, Pin.PULL_UP) btn.irq(trigger=Pin.IRQ_FALLING, handler=btnPressed) def home(): global wifi if wifi.mode() != WLAN.STA: wifi.mode(WLAN.STA) wifi.connect(config.HOME_SSID, auth=(WLAN.WPA, config.HOME_PASSWORD)) def tc(): global t, p import theta t = theta.Theta() p = t.connect() if not p:
states.irq(trigger=Pin.IRQ_RISING, handler=state_change) inc.irq(trigger=Pin.IRQ_RISING, handler=up) while True: if (state == 0): if (sett): now = (2020, 10, 10, 2, hour, minute, 10, 0) rtc.datetime(now) time.sleep(10 * d) sett = False (year, month, date, day, hour, minute, second, p1) = rtc.datetime() if sec_old is not second: SEC.toggle() sec_old = second first_h = int(hour / 10) second_h = int(hour % 10) first_m = int(minute / 10) second_m = int(minute % 10) if (state == 1): CA3.off() CA4.off() SEC.on() lightDigit1(numbers[first_h]) lightDigit2(numbers[second_h]) elif (state == 2): CA1.off()
from machine import Pin import time pin = Pin(25, Pin.OUT) while True: pin.toggle() time.sleep_ms(1000)
# policeLights.py from machine import Pin import utime sleepBetween = 0.3 blinkTime = 0.1 blueLED = Pin(28, Pin.OUT) redLED = Pin(5, Pin.OUT) blueLED.high() redLED.low() while True: for i in range(3): redLED.low() blueLED.toggle() utime.sleep(blinkTime) utime.sleep(sleepBetween) for i in range(3): blueLED.low() redLED.toggle() utime.sleep(blinkTime) utime.sleep(sleepBetween)
def power_test(): ''' Puts the XBee3 into sleep mode for a short amount of time, sends an HTTP request, then puts the device back to sleep. Then we can hook up some hardware instrumentation in order to measure both the quiescent power consumption (sleeping) as well as maximum power consumption (cellular transmitting). ''' print("Launching power test.") from machine import Pin import network import time import urequests import xbee cell = network.Cellular() led = Pin("D5", Pin.OUT, value=0) xb = xbee.XBee() while True: # Put the XBee to sleep. Turn off the LED first to indicate that we're going to sleep. led.value(0) SLEEPTIME_ms = 30000 print("Going to sleep for %s seconds." % str(SLEEPTIME_ms / 1000.0)) xb.sleep_now( SLEEPTIME_ms, pin_wake=False ) # Execution blocks here for the specified time. Device goes into low power mode (NOT the same as time.sleep() which sleeps the thread!) # Now the device is awake. with xb.wake_lock: # Blink the LEDs for 2 seconds to indicate that we've woken up. print("Woke up!") for _ in range(20): led.toggle() time.sleep_ms(100) # Hold on the LED to indicate we're getting ready to transmit. led.value(1) time.sleep_ms(1000) # Attempt to establish cell connection. print("Checking for cell connection.") print("Is active (not airplane mode)? %s" % cell.active()) for _ in range(600): print(".", end="") if cell.isconnected(): break time.sleep_ms(100) if not cell.isconnected(): print("Unable to get cell connection.") for _ in range(8): led.toggle() time.sleep_ms(500) continue # Cell connection was successful! print("Got cell connection!") print(cell.ifconfig()) print("SIM:", cell.config('iccid')) print("IMEI:", cell.config('imei')) print("Provider:", cell.config('operator')) print("Phone #:", cell.config('phone')) print("Cell signal strength: %s" % xbee.atcmd('DB')) # Transmit an HTTP request. try: r = urequests.get("http://api.ipify.org/") print("HTTP response: %s, %s" % (r.status_code, r.text)) except Exception as ex: print("HTTP request failed. Exception: %s" % ex)
from machine import Pin import time onboard_led = Pin(25, Pin.OUT) while True: onboard_led.toggle() time.sleep(1)
import pycom import time from machine import PWM pwm = PWM(0, frequency=50) # use PWM timer 0, with a frequency of 50Hz # create pwm channel on pin P12 with a duty cycle of 50% pwm_c = pwm.channel(0, pin='P12', duty_cycle=0.15) # initialisation code pycom.heartbeat(False) pycom.rgbled(0xCC8080) # pale pink # initialize `P9` in gpio mode and make it an output p_out = Pin('P9', mode=Pin.OUT) p_out.value(1) p_out.value(0) p_out.toggle() p_out(True) # make `P10` an input with the pull-up enabled p_in = Pin('P10', mode=Pin.IN, pull=Pin.PULL_UP) p_in() # get value, 0 or 1 time.sleep(2) while p_in() == 1: pycom.rgbled(0x008000) # Green time.sleep(1) pycom.rgbled(0x000080) # Blue time.sleep(1) p_out.toggle() pwm_c.duty_cycle(0.19) # change the duty cycle to 20%
def tick(timer): global tim led = Pin(25, Pin.OUT) led.toggle()
async def flash_onboard(): # initialize `P9` in gpio mode and make it an output p_out = Pin('P9', mode=Pin.OUT) while True: p_out.toggle() await asyncio.sleep_ms(1000)
print('UART initialised') #uart.irq(trigger=UART.RX_ANY, wake=machine.IDLE) from machine import Pin from machine import Timer led_out = Pin('GP16', mode=Pin.OUT) tim = Timer(1, mode=Timer.PERIODIC) tim_a = tim.channel(Timer.A, freq=5) # The slowest frequency the timer can run at is 5Hz # so we divide the frequency down to toggle the LED # BUT the callback function doesn't appear to have been developed # Worth trying again as it is now included in the documentation tim_a.irq( handler=lambda t: led_out.toggle(), trigger=Timer.TIMEOUT) # Toggle LED on Timer interrupt #btn_in = Pin('GP17', mode=Pin.IN, pull=Pin.PULL_UP) # Connect to my WiFi import machine from network import WLAN wlan = WLAN() # get current object, without changing the mode # Settings for TP-LINK home network KEY = '' IP = '192.168.1.253' # WiPy Fixed IP address GATEWAY = '192.168.1.1' # IP address of gateway DNS = '192.168.1.1' # IP address of DNS NETMASK = '255.255.255.0' # Netmask for this subnet
while keep_looping: try: # print("Any: {}".format(uart.any())) if uart.any(): nmea_string = uart.readline().decode("utf-8") print("NMEA Data: {}".format(nmea_string[:-2])) if (nmea_string.startswith("$GPRMC")): # Filter nb_char_written = log_file.write( nmea_string) # Write it with the CR-NL log_file.flush() log_size += nb_char_written nb_rec += 1 print("\t>> {} record(s) in the log ({:,} bytes)".format( nb_rec, log_size)) # Blink led, to acknowledge led.toggle() except KeyboardInterrupt: keep_looping = False print("Exiting at user's request") led.value(0) # Switch led off break # Theorically useless except OSError as oserr: if str(oserr) == "28": # errno.ENOSPC: now = None if (nmea_string.startswith("$GPRMC")): try: # Get the current date-time from RMC sentence ddmmyy = nmea_string[:-3].split(',')[9] utc = nmea_string[:-3].split(',')[1] now = "{}-{}-{} {}:{}:{} UTC".format(
# test pin init and printing pin = Pin(pin_map[0]) pin.init(mode=Pin.IN) print(pin) pin.init(Pin.IN, Pin.PULL_DOWN) print(pin) pin.init(mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.LOW_POWER) print(pin) pin.init(mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.HIGH_POWER) print(pin) # test value in OUT mode pin = Pin(pin_map[0], mode=Pin.OUT) pin.value(0) pin.toggle() # test toggle print(pin()) pin.toggle() # test toggle again print(pin()) # test different value settings pin(1) print(pin.value()) pin(0) print(pin.value()) pin.value(1) print(pin()) pin.value(0) print(pin()) # test all getters and setters pin = Pin(pin_map[0], mode=Pin.OUT)
oled.text(cmd, 0, 32) # 顯示收到命令內容 reading = voltage.read_u16() * factor # 讀取半固定電阻SVR1電壓並轉換成十進制 oled.text("ADC: ", 5, 8) # 輸出提示字串到OLED,座標(5,8) oled.text(str(round(reading, 2)), 40, 8) # 將電壓值規式化字串輸出到OLED,座標(40,8) oled.show() # 更新OLED顯示區內容 pb1_curr = pb1.value() # 讀取PB1按鍵狀態並放入目前狀態變數中 pb2_curr = pb2.value() # 讀取PB2按鍵狀態並放入目前狀態變數中 if (pb1_curr == 0 and pb1_prev == 1): # 若PB1正緣觸發 print("PB1 Press") # 透過USB Virual COM回傳PB1按下訊息 if (pb1_curr == 1 and pb1_prev == 0): # 若PB1負緣觸發 print("PB1 Release") # 透過USB Virual COM回傳PB1放開訊息 if (pb2_curr == 0 and pb2_prev == 1): # 若PB2正緣觸發 print("PB2 Press") # 透過USB Virual COM回傳PB1按下訊息 if (pb2_curr == 1 and pb2_prev == 0): # 若PB2負緣觸發 print("PB2 Release") # 透過USB Virual COM回傳PB1放開訊息 pb1_prev = pb1_curr # 將PB1目前狀態更新到先前狀態 pb2_prev = pb2_curr # 將PB2目前狀態更新到先前狀態 time_stop = utime.ticks_ms() # 取得目前時間 if utime.ticks_diff(time_stop, time_start) > 500: # 若先前時間比較大於0.5秒 led.toggle() # 則板上LED狀態反轉 time_start = time_stop # 更新目前時間到先前時間
from machine import Pin, ADC import utime adc = ADC(26) TEMPERATURE_SENSOR = ADC(4) CONVERSION_FACTOR = 3.3 / (65535) RED_LED = Pin(21, Pin.OUT) GREEN_LED = Pin(20, Pin.OUT) BLUE_LED = Pin(19, Pin.OUT) LEDS = [RED_LED, GREEN_LED, BLUE_LED] for led in LEDS: led.off() while True: val = adc.read_u16() * CONVERSION_FACTOR reading = TEMPERATURE_SENSOR.read_u16() * CONVERSION_FACTOR temperature = 27 - (reading - 0.706) / 0.001721 print(val) RED_LED.toggle() utime.sleep(2)
from machine import Pin from time import sleep internal_led = Pin(25, Pin.OUT) while True: internal_led.toggle() sleep(0.5)
pin1 = Pin(pins[1], mode=Pin.IN, pull=Pin.PULL_UP) def pin_handler (pin_o): global pin_irq_count_trigger global pin_irq_count_total global _trigger if _trigger & pin1_irq.flags(): pin_irq_count_trigger += 1 pin_irq_count_total += 1 pin_irq_count_trigger = 0 pin_irq_count_total = 0 _trigger = Pin.IRQ_FALLING pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) for i in range (0, 10): pin0.toggle() time.sleep_ms(5) print(pin_irq_count_trigger == 5) print(pin_irq_count_total == 5) pin_irq_count_trigger = 0 pin_irq_count_total = 0 _trigger = Pin.IRQ_RISING pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) for i in range (0, 200): pin0.toggle() time.sleep_ms(5) print(pin_irq_count_trigger == 100) print(pin_irq_count_total == 100) pin1_irq.disable()
os.dupterm(uart) print ('UART initialised') #uart.irq(trigger=UART.RX_ANY, wake=machine.IDLE) from machine import Pin from machine import Timer led_out = Pin('GP16', mode=Pin.OUT) tim = Timer(1, mode=Timer.PERIODIC) tim_a = tim.channel(Timer.A, freq=5) # The slowest frequency the timer can run at is 5Hz # so we divide the frequency down to toggle the LED # BUT the callback function doesn't appear to have been developed # Worth trying again as it is now included in the documentation tim_a.irq(handler=lambda t:led_out.toggle(), trigger=Timer.TIMEOUT) # Toggle LED on Timer interrupt #btn_in = Pin('GP17', mode=Pin.IN, pull=Pin.PULL_UP) # Connect to my WiFi import machine from network import WLAN wlan = WLAN() # get current object, without changing the mode # Settings for TP-LINK home network KEY = '' IP = '192.168.1.253' # WiPy Fixed IP address GATEWAY = '192.168.1.1' # IP address of gateway DNS = '192.168.1.1' # IP address of DNS NETMASK = '255.255.255.0' # Netmask for this subnet
# global value button_pressed_count = 0 # The built-in LED builtin_led = Pin(25, Pin.OUT) button1 = Pin(14, Pin.IN, Pin.PULL_DOWN) # Interrupt Service Routine for Button Pressed Events - with no debounce def button1_pressed(change): global button_pressed_count change.disable_irq() change.delay(50) if button1.value(): button_pressed_count += 1 change.enable_irq() button1.irq(handler=button1_pressed, trigger=Pin.IRQ_FALLING) # | Pin.IRQ_RISING # call the handler function when the value drops from 3.3 to 0 volts on the button pin # button1.irq(handler=button1_pressed, trigger=Pin.IRQ_FALLING ) button_pressed_count_old = 0 while True: if button_pressed_count_old != button_pressed_count: print('Button 1 value:', button_pressed_count) builtin_led.toggle() button_pressed_count_old = button_pressed_count