Using hardware interfaces with Python requires specific binary libraries. Thus, it is not as easily exchangeable among platforms as the hardware-aware part of the code. Below are some hardware-related samples for Python and Micropython.
The following code presents a sample Python application that flashes an LED connected to Raspberry Pi's GPIO pin 16. One must build a circuit (LED + resistor of a proper value) and connect it to the GPIO before running the code.
This example uses a dedicated GPIO handling library (specific for hardware): RPi.GPIO
. For other IoT platforms, this may vary. For example, Micropython uses a Machine
library instead—it covers all the microcontroller's hardware.
import RPi.GPIO as GPIO import time def blink(pin): GPIO.output(pin,GPIO.HIGH) time.sleep(1) GPIO.output(pin,GPIO.LOW) time.sleep(1) return GPIO.setmode(GPIO.BCM) GPIO.setup(16, GPIO.OUT) for i in range(0,5): blink(16) GPIO.cleanup()
A code equivalent for the above algorithm to run in Micropython (here for RP2040) looks quite similar:
import machine import time led=machine.Pin(16, machine.Pin.OUT) def blink(): led.toggle() time.sleep(1) led.toggle() time.sleep(1) led.value(0) for i in range(5): blink()
Similarly to the GPIO, interrupts are hardware-specific; thus, libraries may differ among platforms, hence Python syntax. The sample present below is for Raspberry Pi (regular Python), and the following code is for RPi Pico (RP2040, Micropython).
import RPi.GPIO as GPIO import time led_last = time.time_ns() led_state = GPIO.LOW GPIO.setmode(GPIO.BCM) GPIO.setup(16, GPIO.OUT, initial=led_state) GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) def btnHandler(pin): global led_test, led_state if (led_state==GPIO.LOW): led_state=GPIO.HIGH else: led_state=GPIO.LOW GPIO.output(16, led_state) GPIO.add_event_detect(17, GPIO.FALLING, callback=btnHandler, bouncetime=200) while(True): time.sleep(0)
The sample code for RP2040 Micropython is present below, and its implementation live, via serial port, directly on the MCU is present in the figure 1:
import machine import time import utime led=machine.Pin(16, machine.Pin.OUT) btn=machine.Pin(15, machine.Pin.IN, machine.Pin.PULL_UP) led_last = time.ticks_ms() def btnHandler(pin): global led, led_last, btn if (time.ticks_diff(time.ticks_ms(), led_last)) > 500: led.toggle() led_last=time.ticks_ms() led.value(0) btn.irq(trigger=machine.Pin.IRQ_RISING, handler=btnHandler)