Advertisement
Guest User

Untitled

a guest
Sep 13th, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. import ubinascii, umqtt.robust as MQTTClient, time, math
  2. from machine import Pin, ADC, unique_id
  3.  
  4. pin1 = Pin(4, Pin.OUT)
  5. pin2 = Pin(15, Pin.OUT)
  6. pin3 = Pin(14, Pin.OUT)
  7. pin4 = Pin(12, Pin.OUT)
  8.  
  9. WEIGHT = 10
  10. SUB_TOPIC = b"g11/sub"
  11. PUB_TOPIC = b"g11/pub"
  12.  
  13. CLIENT_ID = ubinascii.hexlify(unique_id())
  14. mqtt = MQTTClient.MQTTClient(CLIENT_ID, "broker.mqtt-cpe.ml", user="None", password="None")
  15.  
  16. _sensor_value = 0
  17.  
  18. def sensor_value():
  19.   _sensor_value = (_sensor_value * (WEIGHT - 1) + ADC(0).read()) / WEIGHT
  20.  
  21.   return _sensor_value
  22.  
  23.  
  24. def turn_on():
  25.   pin1(0)
  26.   pin2(1)
  27.  
  28.  
  29. def turn_off():
  30.   pin1(0)
  31.   pin2(0)
  32.  
  33. def beep(duty=512, period=100):
  34.   beep.duty(duty)
  35.   time.sleep_ms(period)
  36.   beep.duty(0)
  37.  
  38. def onmessage(topic, message):
  39.   if topic == 'turnon':
  40.     turn_on()
  41.   elif topic == 'turnoff':
  42.     turn_off()
  43.  
  44.  
  45. simple_scheduler_timer = time.time()
  46.  
  47. def scheduler_tick(period=1):
  48.   global timesimple_scheduler_timer
  49.  
  50.   if time.time() - timesimple_scheduler_timer < period:
  51.     return False
  52.  
  53.   simple_scheduler_timer = time.time()
  54.  
  55.   return True
  56.  
  57.  
  58. def main():
  59.   mqtt.set_callback(onmessage)
  60.   mqtt.connect()
  61.   mqtt.subscribe(SUB_TOPIC)
  62.  
  63.   while True:
  64.     mqtt.check_msg()
  65.     if scheduler_tick():
  66.       mqtt.publish(PUB_TOPIC, sensor_value())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement