Micropython GPIO控制功能在背景中

发布于 2025-02-10 17:50:53 字数 708 浏览 1 评论 0原文

如何编写代码以允许在我需要的那个时候在后台运行函数? 当我在周期中运行此功能时,它正在追随他人。

import time
from machine import Pin

a_1 = Pin(21, Pin.OUT)
a_2 = Pin(20, Pin.OUT)

def do_something(x):
    print(x)

def some_other_actions():
    time.sleep(10)

def calc_one_two():
    return 1, 2

def func(a, b, on_tmr=2, off_tmr=1):

    a_1.on()
    do_something(a)
    time.sleep_ms(on_tmr)  # sleep for 2ms
    a_1.off()
    time.sleep_ms(off_tmr)  # sleep for 1ms

    a_2.on()
    do_something(b)
    time.sleep_ms(on_tmr)  # sleep for 2ms
    a_2.off()
    time.sleep_ms(off_tmr)  # sleep for 1ms

while True:
    one, two = calc_one_two()
    func(one, two)
    some_other_actions()  # actions that need some time

How can I write code to allow function run in background in exactly that time that I need?
When I run this func in cycle it's executing after others.

import time
from machine import Pin

a_1 = Pin(21, Pin.OUT)
a_2 = Pin(20, Pin.OUT)

def do_something(x):
    print(x)

def some_other_actions():
    time.sleep(10)

def calc_one_two():
    return 1, 2

def func(a, b, on_tmr=2, off_tmr=1):

    a_1.on()
    do_something(a)
    time.sleep_ms(on_tmr)  # sleep for 2ms
    a_1.off()
    time.sleep_ms(off_tmr)  # sleep for 1ms

    a_2.on()
    do_something(b)
    time.sleep_ms(on_tmr)  # sleep for 2ms
    a_2.off()
    time.sleep_ms(off_tmr)  # sleep for 1ms

while True:
    one, two = calc_one_two()
    func(one, two)
    some_other_actions()  # actions that need some time

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉月流沐 2025-02-17 17:50:53

uasyncio 是您应该寻找的。在这里查看文档
https://docs.micropys.micropopys.micropopython.org/en/latest/latest/library/uasyncio-usyncio。 html
波纹管是不同步的闪烁LED的最小样本,正是您在做什么

import uasyncio

async def blink(led, period_ms):
    while True:
        led.on()
        await uasyncio.sleep_ms(5)
        led.off()
        await uasyncio.sleep_ms(period_ms)

async def main(led1, led2):
    uasyncio.create_task(blink(led1, 700))
    uasyncio.create_task(blink(led2, 400))
    await uasyncio.sleep_ms(10_000)


# Running on a generic board
from machine import Pin
uasyncio.run(main(Pin(21), Pin(20)))

uasyncio is what you should look for. Look at documentation here
https://docs.micropython.org/en/latest/library/uasyncio.html
Bellow is minimal sample for blinking leds asynchronously, exactly what you are doing

import uasyncio

async def blink(led, period_ms):
    while True:
        led.on()
        await uasyncio.sleep_ms(5)
        led.off()
        await uasyncio.sleep_ms(period_ms)

async def main(led1, led2):
    uasyncio.create_task(blink(led1, 700))
    uasyncio.create_task(blink(led2, 400))
    await uasyncio.sleep_ms(10_000)


# Running on a generic board
from machine import Pin
uasyncio.run(main(Pin(21), Pin(20)))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文