예제 #1
0
파일: dht.py 프로젝트: redhill42/iota
def restart_and_reconnect():
    print('Failed to connect to MQTT broker. Reconnecting...')
    time.sleep(10)
    machine.reset()


d = dht.DHT11(machine.Pin(15))


def measure_temp(c):
    topic = "api/v1/%s/me/measurement" % MQTT_TOKEN
    try:
        d.measure()
        c.publish(topic, "dht,measure=temp value=%d" % (d.temperature()))
        c.publish(topic, "dht,measure=humi value=%d" % (d.humidity()))
    except:
        pass


try:
    connect_to_wifi()
    client = connect_to_mqtt()
    tmr = Timer(-1)
    tmr.init(period=2000,
             mode=Timer.PERIODIC,
             callback=lambda t: measure_temp(client))
    while True:
        client.wait_msg()
except:
    restart_and_reconnect()
예제 #2
0
파일: timer.py 프로젝트: HotIce0/PAChewie
def init_timers():
    timer_attitude_ctrl = Timer(1)
    timer_attitude_ctrl.init(period=50, mode=Timer.PERIODIC, callback=callback_attitude_ctrl)
    timer_imu_update = Timer(2)
    timer_imu_update.init(period=200, mode=Timer.PERIODIC, callback=callback_imu_update)
time.sleep_ms(500)


def GNSS_info_update(timer):
    GNSS.GNSS_Read()
    GNSS.GNSS_Parese()
    lcd.draw_string(0, 40, "Date: " + GNSS.date, lcd.BLACK, lcd.WHITE)
    lcd.draw_string(0, 60, "UTC Time: " + GNSS.UTC_Time, lcd.BLACK, lcd.WHITE)
    lcd.draw_string(0, 80, "latitude:  " + GNSS.latitude + GNSS.N_S, lcd.BLACK,
                    lcd.WHITE)
    lcd.draw_string(0, 100, "longitude: " + GNSS.longitude + GNSS.E_W,
                    lcd.BLACK, lcd.WHITE)
    lcd.draw_string(0, 120, "Speed: " + str(GNSS.speed_to_groud_kh) + "km/h",
                    lcd.BLACK, lcd.WHITE)
    lcd.draw_string(0, 140,
                    "Course_over_ground: " + str(GNSS.course_over_ground),
                    lcd.BLACK, lcd.WHITE)
    GNSS.print_GNSS_info()


tim = Timer(Timer.TIMER0,
            Timer.CHANNEL0,
            mode=Timer.MODE_PERIODIC,
            period=3000,
            callback=GNSS_info_update)
tim.start()

while True:
    img = sensor.snapshot()
    lcd.display(img)
예제 #4
0
파일: g1.py 프로젝트: pramasoul/ESP-geiger
 def __init__(self, g, log, host='192.168.32.69'):
     self.tim = Timer(-1)
     self.reporter = Reporter(g, host, log)
     self.display = False
예제 #5
0
            0, (addr >> 24) & 0xFF, (addr >> 16) & 0xFF, (addr >> 8) & 0xFF,
            addr & 0xFF
        ]))
    spi.write(data)
    cs.off()
    ctrl(4)
    ctrl(0)


# mount SD can load initial bitstream
try:
    os.mount(SDCard(slot=3), "/sd")
    import ecp5
    #ecp5.prog("/sd/c64/bitstreams/ulx3s_85f_v20_c64_origrom.bit")
except:
    print("check SD and ecp5.py")

# initialization
gc.collect()
init_spi()
alloc_emergency_exception_buf(100)
enable = bytearray(1)
timer = Timer(3)
init_fb()
read_dir()
irq_handler(0)  # service eventual pending/stale IRQ
# activate IRQ service
irq_handler_ref = irq_handler  # allocation happens here
spi_request = Pin(0, Pin.IN, Pin.PULL_UP)
spi_request.irq(trigger=Pin.IRQ_FALLING, handler=irq_handler_ref)
예제 #6
0
    print(dic)
    refind(dic)


def refind(dicc):
    match0 = re.search(r"{\"powerstate\":(.*?)}", dicc)  #获取灯的开关信息
    if match0:
        value0 = eval(match0.group(1))
        led.value(value0)


try:
    client = MQTTClient(CLIENT_ID, SERVER, PORT, username, password, 60)
    print(client)
    client.set_callback(sub_cb)
    client.connect()  #connect mqtt
    client.subscribe(subscribe_TOPIC)
    print("Connected to %s, subscribed to %s topic" %
          (SERVER, subscribe_TOPIC))
    timer = Timer(0)
    timer.init(mode=Timer.PERIODIC, period=5000, callback=Dataupload)
    while True:
        client.wait_msg()

except Exception as ex_results:
    print('exception1', ex_results)

finally:
    if (client is not None):
        client.disconnect()
예제 #7
0
    #print('{3:02d}:{4:02d}:{5:02d}'.format(*localtime))
    #
    oled.fill(0)
    oled.text(haftaninGUNU[localtime[6]], 8, 8)
    oled.text('{0:04d}-{1:02d}-{2:02d}'.format(*localtime), 8, 24)
    oled.text('{3:02d}:{4:02d}:{5:02d}'.format(*localtime), 8, 40)
    #
    oled.show()


#timer objesi olusturmak
def tmr1_kesmesi(timer):
    global dakikasayaci  # global degiskeni localde kullanmak için

    dakikasayaci = dakikasayaci + 1  # bu daha kısa yazılabilir mi?
    if dakikasayaci >= 59:
        ntpGuncelle()
        dakikasayaci = 0

    ntpOLEDyazdir()
    #aga baglımıyım testi
    if wifi.isconnected():
        Led_status.value(1 - Led_status.value())  #yanık
    else:
        Led_status.value(1)  #sonuk


from machine import Timer
tmr1 = Timer(-1)  # sanal zamanlayici olustur
tmr1.init(period=1000, mode=Timer.PERIODIC, callback=tmr1_kesmesi)
#timer objesi olusturmak
예제 #8
0
LEFT_SCROLL = 0x27
DUMMY_BYTE_0 = 0x00
DUMMY_BYTE_F = 0xFF
PAGE_7 = 0x07
FRAMES_5 = 0x00
PAGE_0 = 0x00

# setup pins
button_a = Pin(12, Pin.IN, Pin.PULL_UP)
button_b = Pin(13, Pin.IN, Pin.PULL_UP)
button_c = Pin(14, Pin.IN, Pin.PULL_UP)
adc = ADC(0)
alarm_led= Pin(2, Pin.OUT)

# initalize timers
tim = Timer(-1)
tim2 = Timer(-1)
tim3 = Timer(-1)
tim4 = Timer(-1)
rtc = machine.RTC()

# initialize oled screen
i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000)
oled = ssd1306.SSD1306_I2C(128,32,i2c)
alarm_led.value(not alarm_led.value())

#initialize adxl345
spi = machine.SPI(baudrate=100000, polarity=0, phase=0, sck=machine.Pin(16), mosi=machine.Pin(0), miso=machine.Pin(15))
cs = machine.Pin(2,machine.Pin.OUT)

class My_time(object):
'''
定时器演示实例, 打印定时器,讲解定时器的属性。
'''

from machine import Timer
import utime

timer = Timer(1)


def timer_print(timer):
    # 打印当前的计数
    print("Timer InteruptCount , counter= %d" % (timer.value()))
    print(timer)


'''
定时器 模式:
Timer.ONE_SHOT --- 0                             --         # 执行一次
Timer.PERIODIC --- 1                             --         # 循环执行
'''
# timer.init(period=3000, mode=Timer.PERIODIC , callback=timer_print) #这里直接在回调函数中打印tim状态信息
timer.init(period=1000,
           mode=Timer.PERIODIC,
           callback=lambda t: print("Counter: %d" % (t.value())))

try:
    while True:
        print("do something..., counter = %d" % (timer.value()))
        utime.sleep_ms(100)
except:
예제 #10
0
 def continuous_mode(self):
     self.my_timer = Timer(1)
     self.my_timer.init(period=1000,
                        mode=self.my_timer.PERIODIC,
                        callback=self.my_callback)
예제 #11
0
def sub_cb(topic, msg):
    global sessionID, Sensor_Data, ack
    global temp
    print((topic, msg))

    if topic == b'Sensor_Data':
        Sensor_Data = msg

c = MQTTClient(client_id = ubinascii.hexlify(machine.unique_id()), \
               server = 'm15.cloudmqtt.com',user='******', password='******',port ='16060')
c.set_callback(sub_cb)
c.connect()
c.subscribe(b"Sensor_Data")

####publish message on the sessionID every one second
tim = Timer(0)
counter = 0
ack = 1
temp = 0
temp1 = 0


def handleInterrupt(tim):
    global temp
    global temp1
    global counter
    global ack
    if ack == 1:
        #temp1 = temp
        temp = bytes([random.getrandbits(5)])
예제 #12
0
파일: a.py 프로젝트: PilotXing/8266mqtt
from machine import Timer


def aaa(self):
    """
    docstring
    """
    print("arostnaorien")


t1 = Timer(1)
t1.init(mode=Timer.PERIODIC, period=300, callback=aaa)
예제 #13
0
from machine import Timer
from machine import LED

tim = Timer(1, mode=Timer.PERIODIC)  #创建Timer 1为一个频率定期运行对象
tim_a = tim.channel(Timer.CH_0, freq=1)  #创建Timer A其频率为1Hz

l = LED(1)

led_off = 2
led_on = 3
irq_count = 0


def toggle(t):  #中断回调函数
    global irq_count
    if irq_count < led_off:
        l.off()
    else:
        l.on()
    if irq_count < (led_off + led_on - 1):
        irq_count = irq_count + 1
    else:
        irq_count = 0


tim_a.irq(trigger=Timer.TIMEOUT, handler=toggle)  #回调函数将使用设置的频率定期执行中断
예제 #14
0
import machine
from machine import Pin, Timer
import time

led = Pin(2, Pin.OUT)


def toggleLED(timer):
    led.value(not led.value())


tim4 = Timer(4)
tim4.init(period=300, mode=machine.Timer.PERIODIC, callback=toggleLED)
time.sleep(20)
tim4.deinit()
예제 #15
0
# PWM.
#

##################################################
# import
##################################################
import time
from machine import Timer, PWM
from board import board_info
from fpioa_manager import fm

##################################################
# main
##################################################
# タイマー設定
tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PWM)

# PWM出力ピン設定
ch = PWM(tim, freq=500000, duty=50, pin=board_info.LED_W)

# ループ
duty = 0
dir = True
while True:
    if dir:
        duty += 10
    else:
        duty -= 10
    if 100 < duty:
        duty = 100
        dir = False
예제 #16
0
        raise Exception(
            "Config error: InfluxDB URL is not set. Check configuration")

    if idb is None:
        raise Exception(
            "Config error: InfluxDB Database is not set. Check configuration")

    if imetric is None:
        raise Exception("Config error: InfluxDB Metric is not set")

    influx = InfluxDB(iurl, idb, iusr, ipsw, imetric, place=iplace)
    print("influx: ", iurl, idb)
except Exception as e:
    print("config Exception: {0}".format(e))
    print("Use config.setup()")
    exit(1)

display = disp7_init()

display.show("wifiConn")
net = WiFiConnect()
net.connect()

display.show("timer on")
tim1 = Timer(0)  # for main 10 sec timer
timer_init(tim1)

# --- run ---
print("--- run ---")
# print("RAM free: " + str(mem_free()))
예제 #17
0
    print("Oh Yes! Get connected")
    print("Connected to " + str(wlan.config("essid")))
    print("MAC Address: " + str(ubinascii.hexlify(wlan.config('mac'), ':').decode()))
    print("IP Address: " + wlan.ifconfig()[0])

connect()

#Clock UTC time
ntptime.settime()
rtc = RTC()
year, month, day, weekday, hours, minutes, seconds, microseconds = rtc.datetime()
rtc.datetime((year, month, day, weekday, hours - 4, minutes, seconds, microseconds))
ntptime.host = "pool.ntp.org"

#Hardware timer - 1
tim1 = Timer(1)
tim1.init(period=15000, mode=Timer.PERIODIC, callback=lambda t:printtime(rtc.datetime()))

#Variables
#LEDs
green = Pin(21, Pin.OUT)
red = Pin(32, Pin.OUT)

#Buttons
button_red = Pin(25, Pin.IN, Pin.PULL_DOWN)
button_green = Pin(26, Pin.IN, Pin.PULL_DOWN)

#Touchpad
tpin = TouchPad(Pin(27))
tpin_green = TouchPad(Pin(33))
예제 #18
0
        释放资源
        备注 ADC没有deinit方法
        '''
        # 释放ADC资源
        # self.adc.deinit()
        pass


if __name__ == '__main__':
    '''
    测量电池电压
    '''
    from car_config import gpio_dict
    # from battery_voltage import BatteryVoltage
    from machine import Timer

    bv = BatteryVoltage(gpio_dict['BATTERY_ADC'], is_debug=True)
    # 创建一个定时器
    timer = Timer(1)
    # 每隔100ms执行一次 10s 判断一次电池电压是否过放
    timer.init(period=100, mode=Timer.PERIODIC, callback=bv.callback)

    try:
        while True:
            pass
    except:
        # 释放定时器资源
        timer.deinit()
        # 释放ADC资源
        bv.deinit()
예제 #19
0
import _thread
import padog
import time
from machine import Timer
from machine import UART
from padog import g, m
uart6 = UART(2, 115200)
t = Timer(1)


def OpenMV_Run(t):
    command = ""
    DIS = 0
    if uart6.any():
        read = uart6.read(1).decode('gbk')
        while read != '/':
            command = command + read
            read = uart6.read(1).decode('gbk')
        if (command != "1/") and command != "":
            try:
                exec(command)
                print("exec:", command)
            except:
                print("execerr:", command)
        command = ""


def app_1():
    exec(open('web_c.py').read())

예제 #20
0
    return json


def refresh():
    nowRsp = nowWeather(API_KEY)  #通过API密钥获取天气实况
    dailyRsp = dailyWeather(API_KEY)  #通过API密钥获取多日天气预报

    today = dailyRsp['results'][0]['daily'][0]['date'][-5:]  #当前日期,显示“月-日”
    todayHigh = dailyRsp['results'][0]['daily'][0]['high']  #最高温度
    todaylow = dailyRsp['results'][0]['daily'][0]['low']  #最低温度

    nowText = nowRsp['results'][0]['now']['text']  #天气现象文字
    nowTemper = nowRsp['results'][0]['now']['temperature']  #温度
    todayIco = nowRsp['results'][0]['now']['code']  #天气现象图标
    city = nowRsp['results'][0]['location']['name']  #地理位置

    oled.fill(0)
    oled.bitmap(10, 23, weather_icon.from_code(int(todayIco)), 38, 38,
                1)  #显示当前天气现象图标
    oled.DispChar("%s,天气实况" % city, 0, 0)
    oled.DispChar(today, 90, 0)
    oled.DispChar("%s℃/%s" % (nowTemper, nowText), 70, 25)  #显示当前温度
    oled.DispChar("%s~%s℃" % (todaylow, todayHigh), 70, 45)  #显示今日最低、最高气温
    oled.show()


refresh()  #数据更新

tim1 = Timer(1)
tim1.init(period=1800000, mode=Timer.PERIODIC,
          callback=lambda _: refresh())  #定时,每半个钟刷新一次
예제 #21
0
파일: g1.py 프로젝트: pramasoul/ESP-geiger
 def __init__(self, geiger):
     self.geiger = geiger
     self.tim = Timer(-1)
     self.acc = Accumulator()
     self.display = False
예제 #22
0
_OneNET_msg_list = []


def OneNET_callback(_topic, _msg):
    global _OneNET_msg_list
    try:
        _msg = _msg.decode('utf-8', 'ignore')
    except:
        print(_msg)
        return
    OneNET_recv(_msg)
    if _msg in _OneNET_msg_list:
        eval('OneNET_recv_' + bytes.decode(ubinascii.hexlify(_msg)) + '()')


tim14 = Timer(14)

_iot_count = 0


def timer14_tick(_):
    global _iot, _iot_count
    _iot_count = _iot_count + 1
    if _iot_count == 1000:
        _iot.ping()
        _iot_count = 0
    try:
        _iot.check_msg()
    except:
        machine.reset()
예제 #23
0
# adress i2c module LCD
i2c_address = 0x3F  # decimaal 63

# i2c en lcd instances
i2c = I2C(scl=Pin(21), sda=Pin(22))
lcd = I2cLcd(i2c, i2c_address, 2, 16)

# localtime instance
lt = LocalTime(1, debug=False)

# instellen RTC op esp32
lt.startInternetTime()

# haal iedere seconde de tijd op
timer1 = Timer(0)
timer1.init(period=1000, mode=Timer.PERIODIC, callback=getTime)

try:
    # oneindige lus
    while True:
        # LCD scherm leegmaken
        lcd.clear()
        # toon de tijd op LCD scherm
        lcd.move_to(4, 0)
        lcd.putstr(myGlobals.now)
        # even wachten
        utime.sleep_ms(500)

except Exception as E:
    print('Fout: ', E)
예제 #24
0
button = Pin(34, Pin.IN)

year = int(input("Year? "))
month = int(input("Month? "))
day = int(input("Day? "))
weekday = int(input("Weekday? "))
hour = int(input("Hour? "))
minute = int(input("Minute? "))
second = int(input("Second? "))
microsecond = int(input("Microsecond? "))

rtc = RTC()
rtc.datetime((year, month, day, weekday, hour, minute, second, microsecond))
adc = ADC(Pin(36))
adc.atten(ADC.ATTN_11DB)
tim0 = Timer(0)
week = [
    "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
    "Sunday"
]
tim0.init(period=30000, mode=Timer.PERIODIC, callback=lambda t: display())
tim1 = Timer(1)
tim1.init(period=100, mode=Timer.PERIODIC, callback=lambda t: choice())
pwm0 = PWM(Pin(16), freq=10, duty=256)
pwm1 = PWM(Pin(17), freq=10, duty=256)
mode = 0
prev = 0


def choice():
    if mode == 1:
예제 #25
0
#!/usr/bin/env python
# coding: utf-8
'''
@File   :boot.py
@Author :youxinweizhi
@Date   :2020/7/16
@Github :https://github.com/youxinweizhi
'''

import machine
from machine import Timer
t1 = Timer(2)


def timer_wifi(f):
    if wifi.isconnected():
        pass
    else:
        do_connect()


def is_legal_wifi(essid, password):
    '''
    判断WIFI密码是否合法
    '''
    if len(essid) == 0 or len(password) == 0:
        return False
    return True


def do_connect():
예제 #26
0
from machine import Timer


def on_timer(timer):
    #print("time up:",timer)
    #print("param:",timer.callback_arg())
    timer.callback_arg().state()


try:
    # default: maix dock / maix duino set shift=0
    t = maix_asr(0x500000, I2S.DEVICE_0, 3, shift=0)  # maix bit set shift=1
    tim = Timer(Timer.TIMER0,
                Timer.CHANNEL0,
                mode=Timer.MODE_PERIODIC,
                period=64,
                callback=on_timer,
                arg=t)
    tim.start()

    #for i in range(50):
    #time.sleep_ms(100)
    #t.stop()
    #for i in range(50):
    #time.sleep_ms(100)
    #t.run()

    t.config({
        'xiao-ai-ya': 0.3,
        'hao-de-ya': 0.2,
        'ni-hao-ya': 0.3,
예제 #27
0
class Wifi(object):
    # rtc=Rtc()
    c = None
    ssid = ""
    password = ""
    server = ""
    led = Pin(2, Pin.OUT, value=1)
    button = Pin(0, Pin.IN)
    clients = ubinascii.hexlify(machine.unique_id())
    client = clients.decode()
    topic = b"kembang"
    state = ""
    timer = Timer(0)
    timer2 = Timer(1)
    status = 0
    nyala_pada_1 = ""
    nyala_pada_2 = ""
    nyala_pada_3 = ""
    nyala_pada_4 = ""
    mati_pada_1 = ""
    mati_pada_2 = ""
    mati_pada_3 = ""
    mati_pada_4 = ""
    waktu = ""

    # menit=0
    def __init__(self, *args, **kwargs):
        super(Wifi, self).__init__(*args, **kwargs)
        self.button.irq(trigger=Pin.IRQ_RISING, handler=self.func)
        self.start_ap()
        self.start_mqtt()

    def tim2(self, dt):
        pass

    def func(self, dt):
        self.ap()

    def start_ap(self):
        print("menunggu....")
        time.sleep(5)
        if station.isconnected() == True:
            print("sudah konek")
            return
        self.ap()

    def ap(self):
        self.timer.deinit()
        station.disconnect()
        while (wlan.ifconfig()[0] == '0.0.0.0'):
            time.sleep(1)
        print(wlan.ifconfig())
        try:
            print("tcp sedang menuggu")
            ip = wlan.ifconfig()[0]
            s = socket.socket()
            s.bind(("192.168.4.1", 800))
            s.listen(1)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            station.disconnect()
            while True:
                if self.status == 1:
                    break
                print("acepting....")
                conn, addr = s.accept()
                print(addr, "connected")
                while True:
                    data = conn.recv(1024)
                    if (len(data) == 0):
                        print("close socket")
                        conn.close()
                        break
                    print(data)
                    str_data = data.decode()
                    print(str_data)
                    if "connect" in str_data:
                        print("conceting AP")
                        paket = str_data.split("-")
                        print(paket)
                        t = ("ssid=\"{}\"".format(paket[1]),
                             "pwd=\"{}\"".format(paket[2]),
                             "server=\"{}\"".format(paket[3]))
                        print(t)
                        f = open("net.py", "w")
                        f.write("\n".join(t))
                        f.close()
                        self.server = paket[3]
                        print(self.server)
                        station.connect(paket[1], paket[2])
                        conn.send("data diterima")
                    if str_data == "scan":
                        lis = []
                        nets = station.scan()
                        for nt in nets:
                            name = str(nt[0], 'utf8')
                            lis.append(name)
                            print(lis)
                        conn.send(str(lis))
                    if str_data == "exit":
                        self.status = 1
                        break
                    if str_data == "tanya":
                        print(station.isconnected())
                        if station.isconnected() == True:
                            conn.send("terhubung")
                            return self.start_mqtt()
                            self.status = 1
                            break
                        else:
                            conn.send("belum terhubung")
        except:
            print("gagal c*k")
            if (s):
                s.close()
            wlan.active(False)

    def start_mqtt(self):
        try:
            self.c = MQTTClient(self.clients, net.server)
            self.c.connect()
        except:
            self.c = MQTTClient(self.clients, self.server)
            self.c.connect()
        try:
            print("mulai mqtt")
            self.c.set_callback(self.sub_cb)
            self.c.subscribe(self.topic)
            self.c.subscribe(b"waktu")

            self.c.subscribe(b"nyala_pada_1")
            self.c.subscribe(b"nyala_pada_2")
            self.c.subscribe(b"nyala_pada_3")
            self.c.subscribe(b"nyala_pada_4")

            self.c.subscribe(b"mati_pada_1")
            self.c.subscribe(b"mati_pada_2")
            self.c.subscribe(b"mati_pada_3")
            self.c.subscribe(b"mati_pada_4")

            print("Connected to %s, subscribed to %s topic" %
                  (self.server, self.topic))
            while 1:
                self.timer.deinit()
                self.state = "terhubung"
                self.c.wait_msg()
        except:
            print("pedot")
            self.state = "terputus"
            self.timer.init(period=1000, callback=self.tim)

    def sub_cb(self, topic, msg):
        strtopic = topic.decode()
        message = msg.decode()

        if "waktu" in strtopic:
            self.waktu = message
        elif self.client + "add" in strtopic:
            self.c.publish(self.clients + b"lampu", b"[lampu,on,off]")

        elif self.client + "nyala_pada_1" in strtopic:
            self.nyala_pada_1 = message
        elif self.client + "nyala_pada_2" in strtopic:
            self.nyala_pada_2 = message
        elif self.client + "nyala_pada_3" in strtopic:
            self.nyala_pada_3 = message
        elif self.client + "nyala_pada_4" in strtopic:
            self.nyala_pada_4 = message
        elif self.client + "mati_pada_1" in strtopic:
            self.mati_pada_1 = message
        elif self.client + "mati_pada_2" in strtopic:
            self.mati_pada_2 = message
        elif self.client + "mati_pada_3" in strtopic:
            self.mati_pada_3 = message
        elif self.client + "mati_pada_4" in strtopic:
            self.mati_pada_4 = message
        elif self.waktu == self.nyala_pada_1:
            self.led.value(0)
        elif self.waktu == self.nyala_pada_2:
            self.led.value(0)
        elif self.waktu == self.nyala_pada_3:
            self.led.value(0)
        elif self.waktu == self.nyala_pada_4:
            self.led.value(0)
        elif self.waktu == self.mati_pada_1:
            self.led.value(1)
        elif self.waktu == self.mati_pada_2:
            self.led.value(1)
        elif self.waktu == self.mati_pada_3:
            self.led.value(1)
        elif self.waktu == self.mati_pada_4:
            self.led.value(1)

        elif msg == b"on":
            self.led.value(0)
            # self.c.publish(self.client,b"saya client")
        elif msg == b"off":
            self.led.value(1)
        print(self.waktu)
        print(self.client)
        print(self.nyala_pada_1)

    def tim(self, dt):
        print(station.isconnected())
        if self.state == "terputus":
            self.start_mqtt()
        else:
            self.timer.deinit()
예제 #28
0
# Example using PIO to create a UART TX interface

from machine import Pin, Timer
from rp2 import PIO, StateMachine, asm_pio
import utime

# blink the LED, for the comfort of the viewer:
led = Pin(25, Pin.OUT)
tim = Timer()


def tick(timer):
    global led
    led.toggle()


tim.init(freq=2.5, mode=Timer.PERIODIC, callback=tick)

# do the useful work - flood 8 UARTS with noncence:

#UART_BAUD = 115200
UART_BAUD = 57600
PIN_BASE = 10
NUM_UARTS = 8


@asm_pio(sideset_init=PIO.OUT_HIGH,
         out_init=PIO.OUT_HIGH,
         out_shiftdir=PIO.SHIFT_RIGHT)
def uart_tx():
    # Block with TX deasserted until data available
예제 #29
0
    datetime = rtc.datetime()  # 获取当前时间

    oled.fill(0)  # 清屏显示黑色背景
    oled.text('01Studio', 0, 0)  # 首行显示01Studio
    oled.text('RTC Clock', 0, 15)  # 次行显示实验名称

    # 显示日期,字符串可以直接用“+”来连接
    oled.text(
        str(datetime[0]) + '-' + str(datetime[1]) + '-' + str(datetime[2]) +
        ' ' + week[datetime[3]], 0, 40)

    # 显示时间需要判断时、分、秒的值否小于10,如果小于10,则在显示前面补“0”以达
    # 到较佳的显示效果
    for i in range(4, 7):
        if datetime[i] < 10:
            time_list[i - 4] = "0"
        else:
            time_list[i - 4] = ""

    # 显示时间
    oled.text(
        time_list[0] + str(datetime[4]) + ':' + time_list[1] +
        str(datetime[5]) + ':' + time_list[2] + str(datetime[6]), 0, 55)
    oled.show()


#开启RTOS定时器
tim = Timer(-1)
tim.init(period=300, mode=Timer.PERIODIC, callback=RTC_Run)  #周期300ms
예제 #30
0
    #distance traveled per slot = diameter of wheel = 2pi(2.5/2) / 20 slots = .4 in
    counts_travel = int((-.0000002 * (float(max_code))**2 + .0036 *
                         (float(max_code)) + 2.41 + 2) / .4)
    print('counts_travel: ' + str(counts_travel))

    enc2.clear()
    enc2.resume()
    while enc2.count() < counts_travel:
        print('straight: ' + str(enc2.count()))
        pwm1.duty(100)
        pwm2.duty(60)
        pwm3.duty(100)
        pwm4.duty(60)

    temperature = imu.temperature
    print('temperature: ' + str(temperature))
    topic = "channels/" + "436089" + "/publish/" + "S2L5BJH71OCHNBLN"
    message = "field1={}".format(temperature)

    print("PUBLISH topic = {} message = {}".format(topic, message))
    mqtt.publish(topic, message)

    pwm1.duty(100)
    pwm2.duty(100)
    pwm3.duty(100)
    pwm4.duty(100)


tm = Timer(1)
tm.init(period=7000, mode=tm.PERIODIC, callback=turn)