Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import ubinascii, umqtt.robust as MQTTClient, time, math
- from machine import Pin, ADC, unique_id
- pin1 = Pin(4, Pin.OUT)
- pin2 = Pin(15, Pin.OUT)
- pin3 = Pin(14, Pin.OUT)
- pin4 = Pin(12, Pin.OUT)
- WEIGHT = 10
- WILDCARD_TOPIC = b"g11/#"
- AIR_TOPIC = b"g11/air"
- SENSOR_TOPIC = b"g11/sensor"
- PING_TOPIC = b"g11/ping"
- CLIENT_ID = ubinascii.hexlify(unique_id())
- mqtt = MQTTClient.MQTTClient(CLIENT_ID, "broker.mqtt-cpe.ml", user="None", password="None")
- _sensor_value = 0
- def sensor_value():
- global _sensor_value
- _sensor_value = (_sensor_value * (WEIGHT - 1) + ADC(0).read()) / WEIGHT
- return _sensor_value
- def turn_on():
- pin1(0)
- pin2(1)
- def turn_off():
- pin1(0)
- pin2(0)
- def beep(duty=512, period=100):
- beep.duty(duty)
- time.sleep_ms(period)
- beep.duty(0)
- def onmessage(topic, message):
- message = message.decode("ascii")
- topic = topic.decode("ascii")
- if topic == AIR_TOPIC and message == 'on' :
- turn_on()
- else:
- turn_off()
- simple_scheduler_timer = time.time()
- def scheduler_tick(period=1):
- global timesimple_scheduler_timer
- if time.time() - timesimple_scheduler_timer < period:
- return False
- simple_scheduler_timer = time.time()
- return True
- def main():
- mqtt.set_callback(onmessage)
- mqtt.connect()
- mqtt.subscribe(WILDCARD_TOPIC)
- while True:
- mqtt.check_msg()
- if scheduler_tick():
- mqtt.publish(SENSOR_TOPIC, str(sensor_value()))
- time.sleep(1000)
- mqtt.publish(PING_TOPIC, "iamalive")
- beep()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement