android - 使用 PubNub 为 Raspberry Pi 编写节拍器 Python 脚本

标签 android python raspberry-pi pubnub

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

我的目标是根据 BPM 值在每次节拍时让我的 Raspberry Pi (GPIO 18) 上的 LED 闪烁。正如您在代码中看到的那样。但是,当我启动脚本时。似乎什么都没有发生。 LED 保持关闭状态。 当我尝试打印我的变量数据(例如 BPM 值)时 - 查看是否发生任何事情。我的 Raspberry Pi 上没有弹出任何内容

我不知道我的脚本可能遗漏了什么或有什么问题,因为它也没有给我任何错误消息。 我还验证了我的应用程序通过 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)

最佳答案

我已经找到了解决方案,并且现在可以正常工作。 我会在这里分享。我仍然有一个问题,它因为“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)

关于android - 使用 PubNub 为 Raspberry Pi 编写节拍器 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37515027/

相关文章:

python - 在 Python 中将字符串列表转换为单个字符串

android - 将 GSM/GPRS 调制解调器与带有 Android things 的 Raspberry Pi 3 集成

android - TabActivity 在 Android 4.0 中被弃用( Ice Cream Sandwich )

android - WebView 和 MathML

Android 模拟器不接受我的电脑键盘的输入按钮

python - 如何从 python flask 中的 redis 检索图像

python - 云端代码

raspberry-pi - 树莓派上每分钟 crontab

python - Raspberry PI 3、串行端口和奇怪的响应

apache - 在树莓派上设置 SSL