[Intel Edison] MQTT 簡單範例

上一篇筆記了如何安裝 MQTT 並進行簡單的測試。 接下來,做個小小實驗,利用 Edison 讀取光敏電阻值並顯示於 LCD 上!


硬體需求

Grove - Base Shield Grove - LCD RGB Grove - Light sensor

連接方式

將 Light sensor 接到 Shield 的 A0 上,LCD RGB 接到 Shield 的 I2C


範例程式

Publisher 會讀取 Light Sensor 抓到的數值(這部份是直接拿 mraa 的範例修改),然後利用 MQTT 發出去

這邊用 while 一直跑,感覺要 delay 一下,不過為了交作業,就暫時這樣寫

Publisher 端 Python 程式

#!/usr/bin/env python
import paho.mqtt.client as mqtt
import mraa

_g_cst_ToMQTTTopicServerIP = "localhost"
_g_cst_ToMQTTTopicServerPort = 1883
_g_cst_MQTTTopicName = "MYTOPIC"

def getDate():
    try:
        p = mraa.Aio(0)
        return str(p.readFloat())
    except:
        print "Are you sure you have an ADC ?"
        exit(1)

mqttc = mqtt.Client("python_pub")
mqttc.connect(_g_cst_ToMQTTTopicServerIP, _g_cst_ToMQTTTopicServerPort)
while True:
    mqttc.publish(_g_cst_MQTTTopicName, getDate())

Subscriber 收到資料後,利用 pyupm_i2clcd 將數值顯示在 LCD 上

Subscriber 端 Python 程式

import paho.mqtt.client as mqtt
import mraa
import pyupm_i2clcd as lcd

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("MYTOPIC")
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

myLcd.setCursor(1,0)
myLcd.write(‘Value= ‘+str(msg.payload))

client = mqtt.Client()
myLcd = lcd.Jhd1313m1(0, 0x3E, 0x62)
client.on_connect = on_connect
client.on_message = on_message

client.connect("localhost", 1883, 60)
client.loop_forever()

最後就可以在 LCD 螢幕上看到數值拉~ (速度太快第三位後會看不清楚 XD)

edison2 - [Intel Edison] MQTT 簡單範例

參考資料

Jerry
Jerry

樂於分享的軟體工程師,曾在新創與大型科技公司實習,獲得黑客松競賽冠軍,擔任資安研討會講者。長期熱衷於資訊安全、雲端服務、網路行銷等領域,希望將科技知識分享給更多人。內容轉載請來信:jlee58tw@gmail.com

2 則留言

  1. Python 需要正確排版啊~~~

    import paho.mqtt.client as mqtt
    import mraa
    import pyupm_i2clcd as lcd

    def on_connect(client, userdata, flags, rc):
    print(“Connected with result code “+str(rc))
    client.subscribe(“MYTOPIC”)

    def on_message(client, userdata, msg):
    print(msg.topic+” “+str(msg.payload))
    myLcd.setCursor(1,0)
    myLcd.write(‘Value= ‘+str(msg.payload))

    client = mqtt.Client()
    myLcd = lcd.Jhd1313m1(0, 0x3E, 0x62)
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(“localhost”, 1883, 60)
    client.loop_forever()

發表回應