上一篇筆記了如何安裝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


參考資料

Rotary-Touch-Led-Lcd Sensor Tests

Intel Edison with Grove LCD, temperature sensor and infrared sensor