Skip to content

Commit 7a1599f

Browse files
authored
Merge pull request #1 from Kayden2022/main
新增helloworld、GPIO、外部中断、按键检测等常用示例
2 parents 73db8d6 + 533445c commit 7a1599f

File tree

10 files changed

+426
-1
lines changed

10 files changed

+426
-1
lines changed
+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
"""
2+
Download to the module and run this code manually
3+
"""
4+
import utime
5+
for i in range(60):
6+
print("hello world")
7+
utime.sleep(1)
+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""
2+
Please refer to the Chinese information:https://python.quectel.com/doc/API_reference/zh/
3+
Please refer to English information: https://python.quectel.com/doc/doc/API_reference/en/
4+
"""
5+
"""
6+
This code snippet creates a Python script that utilizes the machine module to set up and handle external
7+
interrupts on two GPIO pins. In this particular example, the first interrupt is triggered by a rising edge
8+
on pin GPIO12 with a pull-down resistor enabled, and the second interrupt is triggered by a falling
9+
edge on pin GPIO13 with a pull-up resistor enabled.
10+
11+
The code defines two callback functions, callback1() and callback2(), that are executed each time an external
12+
interrupt is triggered. Within each callback function, a global variable is incremented to keep track of the
13+
number of times the interrupt has occurred, and the current count and state of the interrupt are printed to the console.
14+
15+
The code also defines a main() function that initializes the global variables, creates the external interrupt objects,
16+
enables the interrupts, and enters an infinite loop. Within this loop, the code pauses for 5 seconds before printing
17+
a message to indicate that the main loop is still running.
18+
19+
Overall, the code demonstrates how to use the machine module to handle external interrupts in a Python script,
20+
making it useful for a variety of sensor input and event-driven applications.
21+
"""
22+
23+
# Importing necessary libraries
24+
from machine import ExtInt # Importing ExtInt module from machine library for external interrupts
25+
import utime # Importing utime module for time control
26+
27+
# Defining callback functions for the two external interrupts
28+
def callback1(args):
29+
global A # Global variable used to count the number of times the first interrupt occurs
30+
A +=1
31+
print('Count A:{},state:{}'.format(A, args)) # Printing the current count and state of the first interrupt
32+
print("callback1")
33+
34+
def callback2(args):
35+
global B # Global variable used to count the number of times the second interrupt occurs
36+
B += 1
37+
print('Count B:{},state:{}'.format(B, args)) # Printing the current count and state of the second interrupt
38+
print("callback2")
39+
40+
def main():
41+
global A # Global variable used by both callback functions
42+
global B # Global variable used by both callback functions
43+
global extint1 # The external interrupt object for the first interrupt
44+
global extint2 # The external interrupt object for the second interrupt
45+
46+
A = 0 # Initializing the first interrupt count
47+
B = 0 # Initializing the second interrupt count
48+
49+
# Creating the first external interrupt object on pin GPIO12 with rising edge trigger and pull-down resistor enabled
50+
extint1 = ExtInt(ExtInt.GPIO12, ExtInt.IRQ_RISING, ExtInt.PULL_PD, callback1)
51+
extint1.enable() # Enabling the first interrupt
52+
53+
# Creating the second external interrupt object on pin GPIO13 with falling edge trigger and pull-up resistor enabled
54+
extint2 = ExtInt(ExtInt.GPIO13, ExtInt.IRQ_FALLING, ExtInt.PULL_PU, callback2)
55+
extint2.enable() # Enabling the second interrupt
56+
57+
while True:
58+
utime.sleep_ms(5000) # Delaying for 5 seconds before continuing
59+
print("main loop running") # Printing a message to indicate that the main loop is still running
60+
61+
if __name__ == '__main__':
62+
main()
63+
64+
65+
66+
+152
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
"""
2+
Please refer to the Chinese information:https://python.quectel.com/doc/API_reference/zh/
3+
Please refer to English information: https://python.quectel.com/doc/doc/API_reference/en/
4+
"""
5+
6+
# Import necessary modules
7+
from machine import ExtInt, Pin
8+
from utime import sleep_ms
9+
from queue import Queue
10+
import _thread
11+
12+
# Create a queue object to hold any events related to pressed keys
13+
key_evt_queue = Queue(8)
14+
15+
# Function to handle and dispatch key events in a separate thread
16+
def key_evt_thread_entry():
17+
while True:
18+
# Wait for an event to be added to the queue
19+
sleep_ms(1)
20+
if not key_evt_queue.empty():
21+
# Retrieve the callback function, pin number, and event type from the queue
22+
event_cb, pin, event = key_evt_queue.get()
23+
# Call the specified callback function with the retrieved parameters
24+
event_cb(pin, event)
25+
26+
# Start a new execution thread running the key event dispatcher function
27+
_thread.start_new_thread(key_evt_thread_entry, ())
28+
29+
# Define a class to abstract the concept of a physical key button
30+
class Key():
31+
32+
# Define constants representing the two types of key events (pressed or released)
33+
class Event():
34+
PRESSED = 0x01
35+
RELEASED = 0x02
36+
37+
# Define a custom exception class to be raised if unexpected values are passed as object parameters
38+
class Error(Exception):
39+
def __init__(self, value):
40+
self.value = value
41+
42+
def __str__(self):
43+
return repr(self.value)
44+
45+
# Constructor method for creating a new Key instance.
46+
# Parameters:
47+
# - pin: The GPIO pin number to which the key is connected
48+
# - level_on_pressed: Sets whether the associated GPIO input pin has a pull-up or pull-down resistor (0 for pull-up, 1 for pull-down)
49+
# - cared_event: A bitfield describing the desired event(s) to be detected by the key object (preferably using the Key.Event constants set earlier)
50+
# - event_cb: A callback function to be executed when a key event is detected
51+
def __init__(self, pin, level_on_pressed, cared_event, event_cb):
52+
# Validate and store the provided parameters
53+
self.pin = pin
54+
if level_on_pressed == 0:
55+
self.exti_pull = ExtInt.PULL_PU
56+
if cared_event == self.Event.PRESSED:
57+
self.exti_trigger_mode = ExtInt.IRQ_FALLING
58+
elif cared_event == self.Event.RELEASED:
59+
self.exti_trigger_mode = ExtInt.IRQ_RISING
60+
elif cared_event == self.Event.PRESSED | self.Event.RELEASED:
61+
self.exti_trigger_mode = ExtInt.IRQ_RISING_FALLING
62+
else:
63+
raise self.Error("Value error of <cared_event>!")
64+
elif level_on_pressed == 1:
65+
self.exti_pull = ExtInt.PULL_PD
66+
if cared_event == self.Event.PRESSED:
67+
self.exti_trigger_mode = ExtInt.IRQ_RISING
68+
elif cared_event == self.Event.RELEASED:
69+
self.exti_trigger_mode = ExtInt.IRQ_FALLING
70+
elif cared_event == self.Event.PRESSED | self.Event.RELEASED:
71+
self.exti_trigger_mode = ExtInt.IRQ_RISING_FALLING
72+
else:
73+
raise self.Error("Value error of <cared_event>!")
74+
else:
75+
raise self.Error("Value error of <level_on_pressed>!")
76+
77+
self.level_on_pressed = level_on_pressed
78+
self.cared_event = cared_event
79+
self.event_cb = event_cb
80+
# Create an external interrupt object on the specified pin using the configured settings and passing the exit_cb method as the ISR
81+
self.exti = ExtInt(self.pin, self.exti_trigger_mode, self.exti_pull, self.exit_cb)
82+
# Enable the interrupt object
83+
self.exti.enable()
84+
85+
# This method is called when a key is triggered by an interrupt.
86+
# It first disables the current ExtInt object and reads the level voltage of the GPIO pin associated with the key.
87+
# Depending on the GPIO voltage level, it determines whether the corresponding event (pressed/released) has occurred.
88+
# The event is then pushed to the shared key event queue in the format of (callback_function, pin_number, event_type).
89+
# The method finishes by re-enabling the ExtInt object for the key.
90+
91+
def exit_cb(self, args):
92+
self.exti.disable() # Disable the current ExtInt object.
93+
sleep_ms(20) # Wait briefly to allow any voltage abnormalities to settle.
94+
95+
gpio = Pin(args[0], Pin.IN, Pin.PULL_PU, 1) # Create a Pin object for the associated GPIO pin.
96+
level = gpio.read() # Read the current GPIO level.
97+
98+
event = None
99+
# Determine if the corresponding event (pressed/released) has occurred based on the GPIO voltage level.
100+
if self.level_on_pressed == 0:
101+
if self.cared_event == self.Event.PRESSED and level == 0:
102+
event = self.cared_event
103+
if self.cared_event == self.Event.RELEASED and level == 1:
104+
event = self.cared_event
105+
if self.cared_event == self.Event.PRESSED | self.Event.RELEASED:
106+
if level == 0:
107+
event = self.Event.PRESSED
108+
else:
109+
event = self.Event.RELEASED
110+
else:
111+
if self.cared_event == self.Event.PRESSED and level == 1:
112+
event = self.cared_event
113+
if self.cared_event == self.Event.RELEASED and level == 0:
114+
event = self.cared_event
115+
if self.cared_event == self.Event.PRESSED | self.Event.RELEASED:
116+
if level == 1:
117+
event = self.Event.PRESSED
118+
else:
119+
event = self.Event.RELEASED
120+
121+
# Add the event to the shared key event queue in the format of (callback function, pin number, event type).
122+
if event:
123+
key_evt_queue.put((self.event_cb, self.pin, event))
124+
125+
# Re-enable the ExtInt object for the key.
126+
self.exti = ExtInt(self.pin, self.exti_trigger_mode, self.exti_pull, self.exit_cb)
127+
self.exti.enable()
128+
129+
# Main entry point of the program. It sets up two GPIO pins as keys (k1 and k2) and registers their events.
130+
# When an event occurs, the event_cb() function is called with arguments specifying the pin and event type.
131+
# The event_cb() function then handles the corresponding key press or release event.
132+
if __name__ == '__main__':
133+
# Set up the GPIO pins for the two keys
134+
k1 = Pin.GPIO4
135+
k2 = Pin.GPIO30
136+
137+
def event_cb(pin, event):
138+
# Handle the key press/release event based on the pin number and event type.
139+
if pin == k1:
140+
if event == Key.Event.PRESSED:
141+
print("k1 pressed")
142+
else:
143+
print("k1 released")
144+
if pin == k2:
145+
if event == Key.Event.PRESSED:
146+
print("k2 pressed")
147+
else:
148+
print("k2 released")
149+
150+
# Register the events for both keys and pass the event callback function.
151+
Key(k1, 0, Key.Event.PRESSED | Key.Event.RELEASED, event_cb)
152+
Key(k2, 0, Key.Event.PRESSED | Key.Event.RELEASED, event_cb)

Official_demo/2_GPIO/GPIO_Keyscan.py

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""
2+
Please refer to the Chinese information:https://python.quectel.com/doc/API_reference/zh/
3+
Please refer to English information: https://python.quectel.com/doc/doc/API_reference/en/
4+
"""
5+
6+
"""
7+
This code is designed to detect when a key button connected to GPIO 12 on a microcontroller has been pressed or released. Its functionality is broken down into separate functions:
8+
9+
timer0_callback(t0) - Executes every 100ms and increments t0Count if it's less than 20.
10+
key_callback(status) - Recognizes if the button has been pressed or released, starts/stops the timer, and prints Long press key or Short press key depending on the length of the press.
11+
thread_KEY() - Monitors the state of the key button continuously using a while loop and calls key_callback(status) accordingly.
12+
The variables and objects used in the functions are defined globally to maintain continuity and accessibility throughout the entire script. Additionally, comments have been added to provide explanations for each function and make the code easier to understand.
13+
"""
14+
15+
from machine import Pin, Timer
16+
import utime
17+
import _thread
18+
19+
# Set up the GPIO object as a global variable for global availability
20+
key = Pin(Pin.GPIO12, Pin.IN, Pin.PULL_PD , 1)
21+
22+
t0Count = 0
23+
24+
def timer0_callback(t0):
25+
# Increment the timer count each time this function is executed
26+
global t0Count
27+
t0Count = t0Count>=20 and t0Count or t0Count + 1
28+
print('t0Count=', t0Count)
29+
30+
# Allocate the Timer object as a global variable to allow for global access
31+
t0 = Timer(Timer.Timer0)
32+
33+
def key_callback(status):
34+
global t0Count
35+
if status == 0: # Key button has been released
36+
print('powerkey release.')
37+
t0.stop() # Stop the timer object
38+
print('t0Count=', t0Count)
39+
if t0Count >= 20:
40+
print('Long press key')
41+
else:
42+
print('Short press key')
43+
44+
t0Count = 0 # Reset the timer count to zero
45+
elif status == 1: # Key button has been pressed
46+
t0.start(period=100, mode=t0.PERIODIC, callback=timer0_callback)
47+
# Start the timer object with a periodic period of 100ms and set its callback function
48+
print('t0Count=', t0Count)
49+
50+
def thread_KEY():
51+
while True:
52+
utime.sleep_ms(20)
53+
if key.read() == 1: # If the key is not pressed, continue
54+
continue
55+
while key.read() == 0: # If the key is pressed down
56+
key_callback(1) # Call the key callback function with value 1 (pressed down)
57+
utime.sleep_ms(20)
58+
key_callback(0) # Call the key callback function with value 0 (released)
59+
60+
_thread.start_new_thread(thread_KEY, ()) # Start a new thread for monitoring the key button
61+
62+
63+
64+
65+

Official_demo/2_GPIO/GPIO_Read.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"""
2+
Please refer to the Chinese information:https://python.quectel.com/doc/API_reference/zh/
3+
Please refer to English information: https://python.quectel.com/doc/doc/API_reference/en/
4+
"""
5+
"""
6+
This code sets up a list of three GPIO objects (connected to pins 11, 12, and 13) with input mode and internal pull-down resistance. It then continuously loops through the list and prints out the current level of each GPIO object. Finally, it delays for 300ms before repeating the loop.
7+
8+
The Pin function is called to create each GPIO object, with the following parameters:
9+
10+
Pin.GPIO11, Pin.GPIO12, Pin.GPIO13 - Specifies the pin number for each GPIO object.
11+
Pin.IN - Sets the GPIO object to input mode.
12+
Pin.PULL_PD - Enables an internal pull-down resistor on the specified pin.
13+
1 - Specifies that the initial value of the pin is high, but input mode this parameter is invalid and can be ignored.
14+
In the main loop, the IOlist is iterated over using a for loop, and the print() function is used to display the state of each GPIO object, along with its pin number and current level. The utime.sleep_ms() function is called to create a delay of 300ms after each loop iteration.
15+
"""
16+
17+
from machine import Pin
18+
import utime
19+
20+
# Set up a list of GPIO objects with input mode and pull-down resistance
21+
IOlist = []
22+
IOlist.append(Pin(Pin.GPIO11, Pin.IN, Pin.PULL_PD , 1))
23+
IOlist.append(Pin(Pin.GPIO12, Pin.IN, Pin.PULL_PD , 1))
24+
IOlist.append(Pin(Pin.GPIO13, Pin.IN, Pin.PULL_PD , 1))
25+
26+
while True:
27+
# Loop through the list of GPIO objects and print out their current level
28+
for x in range(int(len(IOlist))):
29+
print(IOlist[x], 'GPIO{} level'.format(x + 1), end=' : ')
30+
print(IOlist[x].read())
31+
# Delay for 300ms before looping again
32+
utime.sleep_ms(300)
33+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
"""
2+
Please refer to the Chinese information:https://python.quectel.com/doc/API_reference/zh/
3+
Please refer to English information: https://python.quectel.com/doc/doc/API_reference/en/
4+
"""
5+
"""
6+
This code initializes six GPIO objects (connected to pins 34, 32, 31, 1, 2, and 3), with output mode and no internal pull-up/down resistor. It then continuously loops through the list of GPIO objects twice, turning off all the GPIO objects (x.write(1)) before lighting up the next LED (y.write(0)). Finally, there's a delay of 500ms before turning on the next LED.
7+
8+
In the Pin function, the following parameters are used:
9+
10+
Pin.GPIO34, Pin.GPIO32, Pin.GPIO31, Pin.GPIO1, Pin.GPIO2, Pin.GPIO3 - Specifies the pin number for each GPIO object.
11+
Pin.OUT - Sets the GPIO object to output mode.
12+
Pin.PULL_DISABLE - Disables any internal pull-up/down resistor on the specified pin.
13+
0 - Specifies the initial value of the pin as low to light up the LED.
14+
The first for loop iterates through each GPIO object in the IOlist, and the second for loop ensures that all GPIOs are turned off before lighting up the next one with a delay of 500ms using utime.sleep_ms().
15+
"""
16+
17+
from machine import Pin
18+
import utime
19+
20+
# Create an empty list to hold the GPIO objects
21+
IOlist = []
22+
23+
# Initialize each GPIO object with output mode and no internal pull-up/down resistor, and append them to the IOlist
24+
IOlist.append(Pin(Pin.GPIO34, Pin.OUT, Pin.PULL_DISABLE, 0))
25+
IOlist.append(Pin(Pin.GPIO32, Pin.OUT, Pin.PULL_DISABLE, 0))
26+
IOlist.append(Pin(Pin.GPIO31, Pin.OUT, Pin.PULL_DISABLE, 0))
27+
IOlist.append(Pin(Pin.GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0))
28+
IOlist.append(Pin(Pin.GPIO2, Pin.OUT, Pin.PULL_DISABLE, 0))
29+
IOlist.append(Pin(Pin.GPIO3, Pin.OUT, Pin.PULL_DISABLE, 0))
30+
31+
while True:
32+
for y in IOlist: # Loop through each GPIO object in the IOlist
33+
for x in IOlist: # Turn off all GPIO objects before lighting up the next one
34+
x.write(1)
35+
y.write(0) # Light up the current GPIO object
36+
utime.sleep_ms(500) # Wait for 500ms before lighting up the next GPIO object
37+
38+
39+
from machine import Pin
40+
import utime
41+
42+
IOlist = [] # Create an empty list
43+
# Initialize GPIO and add IOlist
44+
IOlist.append(Pin(Pin.GPIO34, Pin.OUT, Pin.PULL_DISABLE, 0))
45+
IOlist.append(Pin(Pin.GPIO32, Pin.OUT, Pin.PULL_DISABLE, 0))
46+
IOlist.append(Pin(Pin.GPIO31, Pin.OUT, Pin.PULL_DISABLE, 0))
47+
IOlist.append(Pin(Pin.GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0))
48+
IOlist.append(Pin(Pin.GPIO2, Pin.OUT, Pin.PULL_DISABLE, 0))
49+
IOlist.append(Pin(Pin.GPIO3, Pin.OUT, Pin.PULL_DISABLE, 0))
50+
51+
52+
while True:
53+
for y in IOlist: # LED lighting one by one
54+
for x in IOlist: # All LED off
55+
x.write(1)
56+
y.write(0) # Light up the LED
57+
utime.sleep_ms(500) # Turn on the next LED after a delay

0 commit comments

Comments
 (0)