用PubNub为树莓派编写的编程节拍器Python脚本

2024-05-16 02:45:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个Android移动应用程序,它通过PubNub发送一个BPM变量(介于0和160之间)。在

我的目标是让我的Raspberry Pi(GPIO 18)上的LED在每一次跳动时闪烁,基于BPM值。正如你在代码中看到的。但是,当我启动脚本时。似乎什么也没发生。LED保持关闭状态。 当我试图打印变量的数据(例如BPM值)时,看看是否发生了什么。我的覆盆子馅饼上什么都没有

我不知道我的脚本可能会丢失或出错,因为它也不会给我任何错误消息。 我还验证了我的应用程序通过PubNub发送数据。在

以下是我目前为止的剧本:

#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import timeit
from threading import Thread
from pubnub import Pubnub
GPIO.setwarnings(False)


GPIO.setmode(GPIO.BOARD)
GPIO.setup(18, GPIO.OUT)

global BlinkLED = 160   

pubnub = Pubnub(publish_key = 'cencored',
subscribe_key = 'cencored')
channel = 'metronoom' 

def _callback(msg, n):

    def BlinkLED(BPM):
        BeatsPerSecond = BPM / 60
        while true:
            strStatus = "LED is turned on"
            GPIO.output(18,False); time.sleep(BeatsPerSecond)
            GPIO.output(18,True)
            strStatus = "LED is turned off"
            print (strStatus)
    BlinkLED(msg['BPM'])    


def _error(m):
    print(m)

pubnub.subscribe(channels=channel, callback=_callback, error=_error)

Tags: fromimport脚本应用程序ledgpiotimedef
1条回答
网友
1楼 · 发布于 2024-05-16 02:45:39

我已经找到了解决办法,现在就可以了。 我在这里分享。我仍然有一个问题,因为“while:True”它被困在一个循环中。当一个新的BPM值被发送到Pi后,我找不到退出循环的方法。所以每次我想要一个不同的节奏,我都要重新运行脚本。在

#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import timeit
from pubnub import Pubnub


pubnub = Pubnub(publish_key = 'pub-c-b03db6ec-221e-483a-9582-9875ca362260',
subscribe_key = 'sub-c-13c8a43a-df92-11e5-aff5-02ee2ddab7fe')
channel = 'metronoom' 

global BPM
global Divider
Divider = 60.000000
Divider2 = 2.000000
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
def BlinkLED(BPM):  
    while True:
        GPIO.setwarnings(False)
        format(BPM, '.6f')
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(18, GPIO.OUT)
        BeatsPerSecond = Divider / BPM
        Interval = BeatsPerSecond / Divider2
        print(BPM)
        print(BeatsPerSecond)
        GPIO.output(18,True)
        GPIO.output(18,False)
        time.sleep(BeatsPerSecond)

def _callback(msg, n):
    print(msg)
    BlinkLED(msg["BPM"])

def _error(m):
    print(m)

pubnub.subscribe(channels=channel, callback=_callback, error=_error)

相关问题 更多 >