예제 #1
0
    def blink_all_timed(self, color, blink_duration, brightness=1):
        """ Blink the entire stand at 2Hz for blink_duration, turns off afterwards
        
        Arguments:
            color : can be 'red', 'green', 'blue', 
                    or a tuple of (r,g,b) where r, g, and b are between 0 and 255
            blink_duration : duration to blink for in seconds
            brightness : between 0 and 1, 0 is off, 1 is full brightness
        """
        start_time = time.ticks_ms()
        
        run_time = time.ticks_diff(time.ticks_ms(), start_time) 
        
        while run_time/1000 < blink_duration:
            if run_time % 500 < 250: 
                self.turn_all_to_color(color, brightness)
            else:
                self.turn_all_off()
            
            time.sleep_ms(1)
            run_time = time.ticks_diff(time.ticks_ms(), start_time) 

        # Ensure that all are off 
        self.turn_all_off()
        
예제 #2
0
파일: stepper.py 프로젝트: Woz4tetra/Atlas
 def step(self, num_steps):
     if time.ticks_diff(self.time0, time.ticks_ms()) > self.delay:
         steps_left = abs(num_steps)
         
         if num_steps > 0: self.direction = True
         if num_steps < 0: self.direction = False
         
         # decrement the number of steps, moving one step each time:
         while steps_left > 0:
             now = time.ticks_us()
             
             # move only if the appropriate delay has passed:
             if time.ticks_diff(self.last_step_time, now) >= self.step_delay:
                 self.last_step_time = now
                 
                 if self.direction:
                     self.step_number += 1
                     if self.step_number == self.step_num:
                         self.step_number = 0
                 else:
                     if self.step_number == 0:
                        self.step_number = self.step_num
                     self.step_number -= 1
                 steps_left -= 1
                 
                 self.step_motor(self.step_number % 4)
         self.time0 = time.ticks_ms()
예제 #3
0
def tst():
    dat = machine.Pin("GP30")
    ow = OneWire(dat)
    ds = FDS1820(ow)
    print("devices:", ds.roms)
    start = time.ticks_ms()
    for x in range(0, 3):
        print("temperatures:", ds.slow_read_temps())
    print(time.ticks_diff(start, time.ticks_ms()))
    start = time.ticks_ms()
    for x in range(0, 3):
        print("temperatures:", ds.read_temps())
    print(time.ticks_diff(start, time.ticks_ms()))
def do_connect():
    import network
    sta_if = network.WLAN(network.STA_IF)
    
    start = time.ticks_ms() # get millisecond counter
    
    
    if not sta_if.isconnected():
        print('Connecting to network...')
        sta_if.active(True)
        sta_if.connect(WIFI_SSID, WIFI_PASSWORD)
        while not sta_if.isconnected():
            print('Waiting for connection...')
            time.sleep_ms(500)
            pin.value(not pin.value()) # Toggle the LED while trying to connect
            
            # compute time difference since we started looking for the network
            # If it's greater than 10s, we'll time out and just start up as 
            # an access point.
            delta = time.ticks_diff(time.ticks_ms(), start) 
            if delta > 10000:
                print('\r\nTimeout on network connection. Please:')
                print(' * check the SSID and password \r\n * connect to the esp8266 Access Point\r\n')
                break
            
    print('Network Configuration:', sta_if.ifconfig())
    pin.high() # Turn off the LED connected
def main():
    # Executed on boot
    global switchPin
    global switchstate
    global lightstate
    switchPin = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)
    cm.setAP(False)   # We don't want AP in work mode by default
    savedData = boot.readSession()
    lightstate = int(savedData[1])
    switchstate = int(savedData[2])
    triac.activate(lightstate)
    print("Bulb reinitialised")
    attemptConnect()

    # Main program
    while(MainLoop):
        global compareTime
        time.sleep_ms(checkFrequency)
        if time.ticks_diff(time.ticks_ms(), compareTime) > reconnAttemptInterval:
            attemptConnect()
            print("Done MQTT connect")
            compareTime = time.ticks_ms()
        if not emergencyMode:
            checkInputChange(0)
            if cm.mqttActive:
                mqtt.check_msg()
        else:
            checkInputChange(1)
예제 #6
0
def _read_timeout(cnt, timeout_ms=2000):
    time_support = "ticks_ms" in dir(time)
    s_time = time.ticks_ms() if time_support else 0
    data = sys.stdin.read(cnt)
    if len(data) != cnt or (time_support and time.ticks_diff(time.ticks_ms(), s_time) > timeout_ms):
        return None
    return data
예제 #7
0
def testProto16():
	start = time.ticks_ms()
	print("Bounce LED on PROTO16-I2C card")

	# Set all of the pins to outputs
	for bit in range(0,16):
		mcp23017.digitalWrite(bit,0)	# preset to zero so LED doesn't blink
		mcp23017.pinMode(bit,mcp23017.OUTPUT)
		if mcp23017.digitalRead(bit)!=0:
			print("testProto16 (1): readback failed - expected 0, got 1")
			sys.exit(1)
		if mcp23017.digitalRead(bit)!=0:
			print("testProto16 (2): readback failed - expected 0, got 1")
			sys.exit(1)
		
	# Blink all LEDs
	for loopCount in range(0,10):
		for bit in range(0,32):
			mcp23017.digitalWrite(bit,1)
			time.sleep(0.5)
			if mcp23017.digitalRead(bit)!=1:
				print("testProto16 (3): readback failed - expected 1, got 0")
				sys.exit(1)
			mcp23017.digitalWrite(bit,0)
	deltaTime = time.ticks_diff(start, time.ticks_ms())/1000
	print("Test completed, time =",abs(deltaTime))
예제 #8
0
    def timeit():
        spi = SpiMaster(1, baudrate=int(pyb.freq()[3] / 16))
        start = ticks_ms()

        for i in range(2 ** 10):
            spi.write_data(b'abcdefgh' * 4)
            spi.read_data()

        print("Millisecond ticks elapsed: %i" % ticks_diff(ticks_ms(), start))
예제 #9
0
 def playing(self):
     """
     Determine if the piano is being played:
     1. A beam interruption (transition from unterrupted to interrupted)
     indicates the start of playing.
     2. It's no longer being played if the inter-note time has passed with
     no subsequent beam interruption
     """
     return self.poll_beam() \
         or self.beam_ever_interrupted \
         and ticks_diff(self.beam_interrupted_t, ticks_ms()) < self.ms_internote 
     """
예제 #10
0
def testDigio128():
	start = time.ticks_ms()
	print("Testing DIGIO-128 card")
	# Set all of the pins to pulled up inputs
	for bit in range(0,128):
		digio128.pinMode(bit,digio128.INPUT_PULLUP)
	# verify all pins were set to pulled up inputs
	for bit in range(0,128):
		if digio128.digitalRead(bit) != 1:
			print("testDigio128(1): Expected pullup on input pin")
			sys.exit(1)
	# Write bits one at a time to 0
	for writtenBit in range(0,128):
		digio128.pinMode(writtenBit,digio128.OUTPUT)
		digio128.digitalWrite(writtenBit,0)
		loopBackBit=writtenBit^0x1f
		# Check all of the pins to be sure only one pin was set to 0
		for checkingBit in range(0,128):
			readValue = digio128.digitalRead(checkingBit)
			# The bit being tested should be 0
			if writtenBit == checkingBit:	# The bit being tested
				if readValue != 0:
					print("testDigio128(2): Expected a 0, got a 1")
					print("testDigio128(2): writtenBit =",writtenBit)
					print("testDigio128(2): checkingBit =",checkingBit)				
					print("testDigio128(2): readValue =",readValue)				
					print("testDigio128(2): loopBackBit =",loopBackBit)
					sys.exit(1)
			# The looped back bit should be 0
			elif checkingBit==loopBackBit:	# The loopback cable here
				if readValue!=0:
					print("testDigio128(3): Expected a 0, got a 1")
					print("testDigio128(3): writtenBit",writtenBit)
					print("testDigio128(3): checkingBit =",checkingBit)				
					print("testDigio128(3): readValue =",readValue)				
					print("testDigio128(3): Expected a 1, got a 0")
					print("testDigio128(3): loopBackBit =",loopBackBit)
					sys.exit(1)
				digio128.digitalWrite(writtenBit,1)
				if digio128.digitalRead(loopBackBit)!= 1:
					print("testDigio128(4): Expected a 1, got a 0")					
				digio128.digitalWrite(writtenBit,0)
			# All the other pins should be 1
			elif readValue!=1:
				print("testDigio128(5): writtenBit =",writtenBit)				
				print("testDigio128(5): checkingBit =",checkingBit)				
				print("testDigio128(5): readValue =",readValue)				
				print("testDigio128(5): Expected a 1, got a 0")
				print("testDigio128(5): loopBackBit =",loopBackBit)
				sys.exit(1)
		digio128.pinMode(writtenBit,digio128.INPUT_PULLUP)
	deltaTime = time.ticks_diff(start, time.ticks_ms())/1000
	print("Test passed, time =",abs(deltaTime))
예제 #11
0
파일: mixgo.py 프로젝트: radiumray/mdxly
 def checkdist(self):
  self.trig.value(0)
  self.echo.value(0)
  self.trig.value(1)
  time.sleep_us(10)
  self.trig.value(0)
  while(self.echo.value()==0):
   pass
  t1=time.ticks_us()
  while(self.echo.value()==1):
   pass
  t2=time.ticks_us()
  return round(time.ticks_diff(t2,t1)/10000*340/2,2)
예제 #12
0
 def wait_response(self):
     start = time.ticks_ms()
     while 1:
         try:
             self.i2c.readfrom_into(self.addr, self.buf1)
             n = self.buf1[0]
             break
         except OSError as er:
             time.sleep_us(500)
         if time.ticks_diff(time.ticks_ms(), start) > 5000:
             raise Exception('timeout')
     if n >= 129:
         raise Exception(n)
     if n == 0:
         return b''
     else:
         return self.i2c.readfrom(self.addr, n)
예제 #13
0
def dl(url, debug=False):
    import uhashlib
    import ubinascii

    proto, dummy, host, path = url.split("/", 3)
    ai = socket.getaddrinfo(host, 80)
    addr = ai[0][4]
    s = socket.socket()
    s.settimeout(10)
    try:
        s.connect(addr)
        s.write(b"GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (path, host))
        size = 0
        hash = uhashlib.sha1()
        t = time.ticks_ms()
        buf = s.read(2000)
        assert buf, buf
        if debug:
            print("initial response:", buf)
        header, buf = buf.split(b"\r\n\r\n", 1)
        #print(header)
        #print(buf)
        hash.update(buf)
        size += len(buf)
        while 1:
            buf = s.read(1024)
            if buf == b"": break
            hash.update(buf)
            size += len(buf)
            sys.stdout.write("%dK\r" % (size >> 10))
#            sta.active(False)
        delta = time.ticks_diff(time.ticks_ms(), t)
        #print()
        print("Size :", size)
        print("Speed: %s bytes/s" % (size / delta * 1000))
        print("Elapsed: %s" % (delta / 1000))
        sha = str(ubinascii.hexlify(hash.digest()), "ascii")
        print("SHA1 :", sha)
        return size, sha
    finally:
        s.close()
예제 #14
0
def pktgen(displaycb):
    broadcast_addr = "255.255.255.255"
    print("       sending to: {} {} every {} seconds"
        .format(broadcast_addr, artnet_port, DELAY))

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    pktdata = []

    start = time.ticks_ms()
    while True:
        #pktdata = os.urandom(512)
        if time.ticks_diff(start, time.ticks_ms()) > 500:
            sock.sendto(gen_artnet_pkt(pktdata, universe), (broadcast_addr, artnet_port))
            start = time.ticks_ms()

        if displaycb: 
            pktdata = displaycb(pktdata)
        #time.sleep(DELAY)
        if not transmitter:
            print("no more transmitting")
            return
예제 #15
0
	def changingEdge(self, pin):
		global callback

		# Get the flag which enabled to IRQ
		flags = callback.flags()
		# If rising, start count the time
		if flags & Pin.IRQ_RISING:
			self.raising_time = time.ticks_us()
		# If falling edge, then stop counting the time and calculate the distance
		elif flags & Pin.IRQ_FALLING:
			self.falling_time = time.ticks_us()
			# Get the ellapsed time between RISING and FALLING
			delay = time.ticks_diff(self.raising_time, self.falling_time)
			# We use 17 instead of 0,017
			distance = delay * 17
			# We rescale the distance in cm by separating cm and mm
			self.cm = distance // 1000
			self.mm = distance % 1000
		
			#in case we have a distance like 49028
			# cm = 49
			# mm = 028 but the 0 would be discared so we check it
			if distance % 100 == distance % 1000:
				self.mm_decimal = "0"
예제 #16
0
def test_features(lcd, orient=lcd160cr.PORTRAIT):
    # if we run on pyboard then use ADC and RTC features
    try:
        import pyb
        adc = pyb.ADCAll(12, 0xf0000)
        rtc = pyb.RTC()
    except:
        adc = None
        rtc = None

    # set orientation and clear screen
    lcd = get_lcd(lcd)
    lcd.set_orient(orient)
    lcd.set_pen(0, 0)
    lcd.erase()

    # create M-logo
    mlogo = framebuf.FrameBuffer(bytearray(17 * 17 * 2), 17, 17, framebuf.RGB565)
    mlogo.fill(0)
    mlogo.fill_rect(1, 1, 15, 15, 0xffffff)
    mlogo.vline(4, 4, 12, 0)
    mlogo.vline(8, 1, 12, 0)
    mlogo.vline(12, 4, 12, 0)
    mlogo.vline(14, 13, 2, 0)

    # create inline framebuf
    offx = 14
    offy = 19
    w = 100
    h = 75
    fbuf = framebuf.FrameBuffer(bytearray(w * h * 2), w, h, framebuf.RGB565)
    lcd.set_spi_win(offx, offy, w, h)

    # initialise loop parameters
    tx = ty = 0
    t0 = time.ticks_us()

    for i in range(300):
        # update position of cross-hair
        t, tx2, ty2 = lcd.get_touch()
        if t:
            tx2 -= offx
            ty2 -= offy
            if tx2 >= 0 and ty2 >= 0 and tx2 < w and ty2 < h:
                tx, ty = tx2, ty2
        else:
             tx = (tx + 1) % w
             ty = (ty + 1) % h

        # create and show the inline framebuf
        fbuf.fill(lcd.rgb(128 + int(64 * math.cos(0.1 * i)), 128, 192))
        fbuf.line(w // 2, h // 2,
            w // 2 + int(40 * math.cos(0.2 * i)),
            h // 2 + int(40 * math.sin(0.2 * i)),
            lcd.rgb(128, 255, 64))
        fbuf.hline(0, ty, w, lcd.rgb(64, 64, 64))
        fbuf.vline(tx, 0, h, lcd.rgb(64, 64, 64))
        fbuf.rect(tx - 3, ty - 3, 7, 7, lcd.rgb(64, 64, 64))
        for phase in (-0.2, 0, 0.2):
            x = w // 2 - 8 + int(50 * math.cos(0.05 * i + phase))
            y = h // 2 - 8 + int(32 * math.sin(0.05 * i + phase))
            fbuf.blit(mlogo, x, y)
        for j in range(-3, 3):
            fbuf.text('MicroPython',
                5, h // 2 + 9 * j + int(20 * math.sin(0.1 * (i + j))),
                lcd.rgb(128 + 10 * j, 0, 128 - 10 * j))
        lcd.show_framebuf(fbuf)

        # show results from the ADC
        if adc:
            show_adc(lcd, adc)

        # show the time
        if rtc:
            lcd.set_pos(2, 0)
            lcd.set_font(1)
            t = rtc.datetime()
            lcd.write('%4d-%02d-%02d %2d:%02d:%02d.%01d' % (t[0], t[1], t[2], t[4], t[5], t[6], t[7] // 100000))

        # compute the frame rate
        t1 = time.ticks_us()
        dt = time.ticks_diff(t1, t0)
        t0 = t1

        # show the frame rate
        lcd.set_pos(2, 9)
        lcd.write('%.2f fps' % (1000000 / dt))
예제 #17
0
                            if (avg_desync < 0):
                                chrono.stop()
                                time.sleep_ms(abs(int(avg_desync)))
                                chrono.start()
                                avg_desync = 0
                            lora.power_mode(LoRa.SLEEP)
                            active += (chrono.read_ms() - sync_start)
                            time.sleep_ms(guard)
                            rec = 1
                        except ValueError:  # alternative sync method
                            if (str(s_msg) == "sync"):
                                print("sync received!")
                                lora.power_mode(LoRa.SLEEP)
                                active += (chrono.read_ms() - sync_start)
                                time.sleep_ms(guard - 1)
                                rec = 1
            print("sync slot lasted:",
                  abs(time.ticks_diff(int(chrono.read_ms()), int(sync_start))),
                  "ms")
            pycom.rgbled(blue)
        finish = chrono.read_ms()
        print("round lasted:", abs(time.ticks_diff(int(finish), int(start))),
              "ms")
        print("Current active time", active, "ms")
        i += 1

    print("Total active time", active, "ms")
    pycom.rgbled(off)
    lora_sock.close()
    time.sleep(20)
예제 #18
0
spot_test(          1,  (2000,  1,  1,  0,  0,  1, 5,   1))
spot_test(         59,  (2000,  1,  1,  0,  0, 59, 5,   1))
spot_test(         60,  (2000,  1,  1,  0,  1,  0, 5,   1))
spot_test(       3599,  (2000,  1,  1,  0, 59, 59, 5,   1))
spot_test(       3600,  (2000,  1,  1,  1,  0,  0, 5,   1))
spot_test(         -1,  (1999, 12, 31, 23, 59, 59, 4, 365))
spot_test(  447549467,  (2014,  3,  7, 23, 17, 47, 4,  66))
spot_test( -940984933,  (1970,  3,  7, 23, 17, 47, 5,  66))
spot_test(-1072915199,  (1966,  1,  1,  0,  0,  1, 5,   1))
spot_test(-1072915200,  (1966,  1,  1,  0,  0,  0, 5,   1))
spot_test(-1072915201,  (1965, 12, 31, 23, 59, 59, 4, 365))

t1 = time.time()
time.sleep(2)
t2 = time.time()
print(time.ticks_diff(t1, t2) == 2)

t1 = time.ticks_ms()
time.sleep_ms(50)
t2 = time.ticks_ms()
print(time.ticks_diff(t1, t2) == 50)

t1 = time.ticks_us()
time.sleep_us(1000)
t2 = time.ticks_us()
print(time.ticks_diff(t1, t2) < 2000)

t1 = time.ticks_cpu()
t2 = time.ticks_cpu()
print(time.ticks_diff(t1, t2) < 16384)
예제 #19
0
# ble初始化
ble.init('PPT_Remote')
# 等待蓝牙主机
sleep(2)

while True:
    # 当按键A为低电平且标志为0
    if button_a.value() == 0 and btn_a_status == 0:
        btn_a_time = time.ticks_ms()
        # 按键保持标志
        a_hold_flag = False
        # 当按键一直按下
        while not button_a.value():
            # 当按下保持2秒
            if time.ticks_diff(time.ticks_ms(), btn_a_time) > 2000:
                # 发送 F5,放映幻灯片
                ble.hidd_send_keyboard([ble.HID_KEY_F5])
                print("Pressed F5")
                # 按键保持标志置为1
                a_hold_flag = True
                break
        # 如果没有持续按下按键
        if a_hold_flag is False:
            # 发送 LeftArrow,幻灯片上页
            ble.hidd_send_keyboard([ble.HID_KEY_LEFT_ARROW])
            print("Pressed LeftArrow")
        # 按键状态置为1
        btn_a_status = 1

    # 当按键A为高电平且标志为1时,释放按键
예제 #20
0
def sleep_from_until(start, delay):
    while time.ticks_diff(start, time.ticks_ms()) < delay:
        idle_func()
    return start + delay
예제 #21
0
from time import ticks_ms, ticks_diff
topic = b'16/16'
startTime = ticks_ms()
for i in range(1000):
    #	entry = len(topic)
    #	entry = topic[2]
    folder, entry = topic.split(b'/')
endTime = ticks_ms()
print(ticks_diff(startTime, endTime))
예제 #22
0
 def micros(self):
     return round(time.ticks_diff(self.t_end, self.t_ini), 0)
예제 #23
0
def test_features(lcd, orient=lcd160cr.PORTRAIT):
    # if we run on pyboard then use ADC and RTC features
    try:
        import pyb

        adc = pyb.ADCAll(12, 0xF0000)
        rtc = pyb.RTC()
    except:
        adc = None
        rtc = None

    # set orientation and clear screen
    lcd = get_lcd(lcd)
    lcd.set_orient(orient)
    lcd.set_pen(0, 0)
    lcd.erase()

    # create M-logo
    mlogo = framebuf.FrameBuffer(bytearray(17 * 17 * 2), 17, 17,
                                 framebuf.RGB565)
    mlogo.fill(0)
    mlogo.fill_rect(1, 1, 15, 15, 0xFFFFFF)
    mlogo.vline(4, 4, 12, 0)
    mlogo.vline(8, 1, 12, 0)
    mlogo.vline(12, 4, 12, 0)
    mlogo.vline(14, 13, 2, 0)

    # create inline framebuf
    offx = 14
    offy = 19
    w = 100
    h = 75
    fbuf = framebuf.FrameBuffer(bytearray(w * h * 2), w, h, framebuf.RGB565)
    lcd.set_spi_win(offx, offy, w, h)

    # initialise loop parameters
    tx = ty = 0
    t0 = time.ticks_us()

    for i in range(300):
        # update position of cross-hair
        t, tx2, ty2 = lcd.get_touch()
        if t:
            tx2 -= offx
            ty2 -= offy
            if tx2 >= 0 and ty2 >= 0 and tx2 < w and ty2 < h:
                tx, ty = tx2, ty2
        else:
            tx = (tx + 1) % w
            ty = (ty + 1) % h

        # create and show the inline framebuf
        fbuf.fill(lcd.rgb(128 + int(64 * math.cos(0.1 * i)), 128, 192))
        fbuf.line(
            w // 2,
            h // 2,
            w // 2 + int(40 * math.cos(0.2 * i)),
            h // 2 + int(40 * math.sin(0.2 * i)),
            lcd.rgb(128, 255, 64),
        )
        fbuf.hline(0, ty, w, lcd.rgb(64, 64, 64))
        fbuf.vline(tx, 0, h, lcd.rgb(64, 64, 64))
        fbuf.rect(tx - 3, ty - 3, 7, 7, lcd.rgb(64, 64, 64))
        for phase in (-0.2, 0, 0.2):
            x = w // 2 - 8 + int(50 * math.cos(0.05 * i + phase))
            y = h // 2 - 8 + int(32 * math.sin(0.05 * i + phase))
            fbuf.blit(mlogo, x, y)
        for j in range(-3, 3):
            fbuf.text(
                "MicroPython",
                5,
                h // 2 + 9 * j + int(20 * math.sin(0.1 * (i + j))),
                lcd.rgb(128 + 10 * j, 0, 128 - 10 * j),
            )
        lcd.show_framebuf(fbuf)

        # show results from the ADC
        if adc:
            show_adc(lcd, adc)

        # show the time
        if rtc:
            lcd.set_pos(2, 0)
            lcd.set_font(1)
            t = rtc.datetime()
            lcd.write("%4d-%02d-%02d %2d:%02d:%02d.%01d" %
                      (t[0], t[1], t[2], t[4], t[5], t[6], t[7] // 100000))

        # compute the frame rate
        t1 = time.ticks_us()
        dt = time.ticks_diff(t1, t0)
        t0 = t1

        # show the frame rate
        lcd.set_pos(2, 9)
        lcd.write("%.2f fps" % (1000000 / dt))
 def is_timedout(self, timeout_time):
     """A platform specific test of the timeout time."""
     # micropython ticks_diff(ticks1, ticks2) has the same meaning as ticks1 - ticks2
     return time.ticks_diff(time.ticks_ms(), timeout_time) >= 0
예제 #25
0
def update_display():
    quokka.display.fill(0)  # clear the display
    draw_metronome()
    draw_bpm()
    quokka.display.show()  # show the display


start_flash_beat()
update_display()
while True:
    current_time = time.ticks_ms()
    update_display()

    # flash_duration after the last beat
    if time.ticks_diff(current_time, last_beat_time) > flash_duration_ms:
        finish_flash_beat()

    # beat_duration after the last beat
    if time.ticks_diff(current_time, last_beat_time) > beat_duration_ms:
        next_beat()
        start_flash_beat()

    if quokka.button_a.was_pressed():
        change_bpm(-10)
        reset()

    if quokka.button_b.was_pressed():
        change_bpm(10)
        reset()
예제 #26
0
chip = MCP3008(spi, cs)

state = True

offset_n = 0
offset_z = 0

t0 = ticks_ms()

fill_mem_slot(offset_n, offset_z)
#fill_mem_slot_1(offset_n, offset_z)
#d0.READ_ADDR = addressof(mem_slot_1)
#ar_p[0] = addressof(mem_slot_1)

t1 = ticks_ms()
print(ticks_diff(t1, t0))


@rp2.asm_pio(
    # GP6, GP7, GP8, GP9 = kurbelwelle, zuendung, nockewelle, debug
    out_init=(rp2.PIO.OUT_LOW, rp2.PIO.OUT_LOW, rp2.PIO.OUT_LOW,
              rp2.PIO.OUT_LOW),
    #out_init=(rp2.PIO.OUT_HIGH, rp2.PIO.OUT_LOW, rp2.PIO.OUT_LOW),
    #out_init=(rp2.PIO.OUT_LOW),
    out_shiftdir=rp2.PIO.SHIFT_LEFT,
    autopull=True,
    pull_thresh=32,
)
def signal():
    wrap_target()
    #out(x, 1)
예제 #27
0
"""Main 
"""
last_upd_time = 0
while True:
    # update current mode
    if not board.is_calibration_mode() and board.is_calibration_on():
        print('set to calibration mode')
        board.set_to_calibration_mode()
    elif board.is_calibration_mode() and not board.is_calibration_on():
        print('set to normal mode')
        board.set_to_normal_mode()

    # normal mode
    if not board.is_calibration_mode():
        now = time.ticks_ms()
        delta = time.ticks_diff(now, last_upd_time)
        print('delta_t: {}'.format(delta))
        if delta > delay_upd * 1000:
            last_upd_time = now
            is_below, value = board.is_moisture_below_thresh()
            print('moisture {}'.format(value))
            client.send_data('moisture-sensor', value)
            if board.is_normal_mode() and is_below:
                print('set to below thresh mode')
                board.set_to_below_thresh_mode()
            elif board.is_below_mode() and not is_below:
                print('set to normal mode')
                board.set_to_normal_mode()
        board.np_animate_update()

    # calibration mode. nothing to do on update
예제 #28
0
파일: weather.py 프로젝트: tve/mpy-weather
async def query_sensors(client, topic, interval):
    global bme680, si7021, sht31, pmsx003, anemo, vane, rain
    global cwop, display
    global pm_cnt, pm_sum
    global mode
    t0 = time.ticks_ms()
    while True:
        data = {}
        gas, pm25 = None, None
        # convert the bme680
        if bme680:
            await asyncio.sleep_ms(bme680.convert())
            while not bme680.ready():
                await asyncio.sleep_ms(10)
            (t, h, p, gas) = bme680.read_data()
            tF = t * 1.8 + 32
            log.info("BME680 : T=%.1f°F H=%.0f%% P=%.3fmBar G=%.3fkΩ", tF, h, p, gas / 1000)
            (data["t_bme680"], data["h_bme680"]) = (t, h)
            (data["p_bme680"], data["g_bme680"]) = (p / 1000, gas)
        # read the si7021
        if si7021:
            await asyncio.sleep_ms(si7021.convert() + 2)
            (t, h) = si7021.read_temp_humi()
            log.info("Si7021 : T=%.1f°F H=%.0f%%", t * 1.8 + 32, h)
            (data["t_si7021"], data["h_si7021"]) = (t, h)
        # read sht31
        if sht31:
            await asyncio.sleep_ms(sht31.convert() + 2)
            (t, h) = sht31.read_temp_humi()
            log.info("SHT31  : T=%.1f°F H=%.0f%%", t * 1.8 + 32, h)
            (data["t_sht31"], data["h_sht31"]) = (t, h)
        # read wind
        if anemo:
            (w, g) = anemo.read()
            logstr = "Wind   : %.0fmph gust:%.0fmph"
            logvars = [w, g]
            (data["wind"], data["gust"]) = (w*0.44704, g*0.44704) # in m/s
            if vane:
                d = vane.read()
                logstr += " dir=%0f°"
                logvars.append(d)
                data["wdir"] = d
            log.info(logstr, *logvars)
        # read rain gauge
        # TODO!

        # insert averaged dust data
        if pm_cnt > 0:
            d = [v / pm_cnt for v in pm_sum]
            pm25 = d[0]
            data["pm25"] = pm25
            log.info("PMSx003: D=%.1fµg/m³ X=%.1f", d[0], d[1])
            pm_sum = [0 for _ in pm_sum]
            pm_cnt = 0

        # AQI conversions
        if gas is not None:
            data["aqi_tvoc"] = aqi.tvoc_bme680(gas)
        if pm25 is not None:
            data["aqi_pm25"] = aqi.pm25(pm25)

        if display:
            display.fill(0)
            if mode == 1:
                # Test mode for wind vane
                wdir = data.get("wdir", -1)
                display.text("Wind dir: %d" % wdir, 0, 0)
                wdir_str = "%3do" % wdir
                seg7.draw_number(display, wdir_str, 10, 14, 18, 48, 1, 3)

            elif mode == 2:
                # Test mode for wind speed
                wspd = data.get("wind", -1) * 2.237
                display.text("Wind: %.1f mph" % wspd, 0, 0)
                wspd_str = "%4.1f" % (wspd/2.5)
                seg7.draw_number(display, wspd_str, 10, 14, 18, 48, 1, 3)

            # else mode == 3: # regular function is rapid update test mode, "falls thru" into else
            # else mode == 4: # regular function 1 quick update then switch to mode 0, "falls thru"

            else:
                # Regular operating mode, display lots of data and send it too

                # publish data
                if mode == 0 and any(d is not None for d in data):
                    log.debug("pub: %s", data)
                    await client.publish(topic, json.dumps(data), qos=1, sync=False)

                # display data
                display.text(
                    "BME {:.1f}F {:.0f}%".format(data["t_bme680"] * 1.8 + 32, data["h_bme680"]),
                    0,
                    0,
                )
                display.text(
                    "    {:.0f}mB {:.0f}kO".format(
                        data["p_bme680"] * 1000, data["g_bme680"] / 1000
                    ),
                    0,
                    9,
                )
                display.text(
                    "SHT {:.1f}F {:.0f}%".format(data["t_sht31"] * 1.8 + 32, data["h_sht31"]),
                    0,
                    18,
                )
                display.text(
                    "Si  {:.1f}F {:.0f}%".format(data["t_si7021"] * 1.8 + 32, data["h_si7021"]),
                    0,
                    27,
                )
                display.text("PM  {:.1f} Rn {:.2f}".format(data.get("pm25", -1), 0), 0, 36)
                display.text(
                    "Wnd {:.0f} {:3d}*".format(data.get("wind", -1), data.get("wdir", -1)), 0, 45
                )
                display.text("Free {:d} {:d}".format(gc.mem_free(), gc.mem_maxfree()), 0, 54)

            if mode_led:
                await mode_blink()
            display.show()

        if mode == 0 and cwop:
            asyncio.get_event_loop().create_task(
                cwop(
                    temp=data.get("t_bme680", None),
                    hum=data.get("h_bme680", None),
                    baro=data.get("p_bme680", None),
                    winddir=data.get("wdir", None),
                    windspeed=data.get("wind", None),
                    windgust=data.get("gust", None),
                )
            )

        # sleep
        iv = interval
        while True:
            t1 = time.ticks_ms()
            dt = time.ticks_diff(t1, t0)
            if dt >= iv or mode and dt > mode_period[mode]:
                break
            await asyncio.sleep_ms(min(iv - dt, 500))
        if dt >= iv and dt < iv * 3 / 2:
            t0 = time.ticks_add(t0, iv)
        else:
            t0 = time.ticks_ms()
        if mode > mode_max:  # hack to get mode 0 to display immediately when switching to it
            mode = 0
예제 #29
0
    # Ping test
    res.close()


# Led pin
led = machine.Pin(config.LED_PIN, machine.Pin.OUT)

# Initializing Network
# Need to consider SZZX
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
led.off()
start = time.ticks_ms()
sta_if.connect(config.SSID, config.passwd)
while not sta_if.isconnected():
    if time.ticks_diff(time.ticks_ms(), start) > 100000:
        print('Fail to connect to ', config.SSID)
        break
led.on()

# Connect to SMS WIFI
# szzx_connection()

# Connect to server
global mqclient
mqclient = mqtt.MQTTClient(config.MQTT_ID,config.MQTT_SERVER,\
 port=config.MQTT_PORT,user=config.MQTT_USER,password=config.MQTT_PASSWD,\
 ssl=config.MQTT_SSL)
led.off()
res = mqclient.connect()
start = time.ticks_ms()
예제 #30
0
test()
spot_test(          0,  (2000,  1,  1,  0,  0,  0, 5,   1))
spot_test(          1,  (2000,  1,  1,  0,  0,  1, 5,   1))
spot_test(         59,  (2000,  1,  1,  0,  0, 59, 5,   1))
spot_test(         60,  (2000,  1,  1,  0,  1,  0, 5,   1))
spot_test(       3599,  (2000,  1,  1,  0, 59, 59, 5,   1))
spot_test(       3600,  (2000,  1,  1,  1,  0,  0, 5,   1))
spot_test(         -1,  (1999, 12, 31, 23, 59, 59, 4, 365))
spot_test(  447549467,  (2014,  3,  7, 23, 17, 47, 4,  66))
spot_test( -940984933,  (1970,  3,  7, 23, 17, 47, 5,  66))
spot_test(-1072915199,  (1966,  1,  1,  0,  0,  1, 5,   1))
spot_test(-1072915200,  (1966,  1,  1,  0,  0,  0, 5,   1))
spot_test(-1072915201,  (1965, 12, 31, 23, 59, 59, 4, 365))

t1 = time.time()
time.sleep(2)
t2 = time.time()
print(abs(time.ticks_diff(t1, t2) -2) <= 1)

t1 = time.ticks_ms()
time.sleep_ms(50)
t2 = time.ticks_ms()
print(abs(time.ticks_diff(t1, t2)- 50) <= 1)

t1 = time.ticks_us()
time.sleep_us(1000)
t2 = time.ticks_us()
print(time.ticks_diff(t1, t2) < 1500)

print(time.ticks_diff(time.ticks_cpu(), time.ticks_cpu()) < 16384)
예제 #31
0
def test_insert_multiple_rows():
    try:
        if uC:
            gc.collect()
            before = gc.mem_free()
            start_time = time.ticks_ms()
        db_object = mdb.Database.open("testdb")
        if uC:
            gc.collect()
            after = gc.mem_free()
            end_time = time.ticks_diff(time.ticks_ms(), start_time)
            print("Database open took", end_time, "ms to run.")
            print("Database open took up", before - after, "bytes.")
            gc.collect()
            before = gc.mem_free()
            start_time = time.ticks_ms()
        db_table = db_object.open_table("testtable")
        if uC:
            gc.collect()
            after = gc.mem_free()
            end_time = time.ticks_diff(time.ticks_ms(), start_time)
            print("Opening table with 550 rows took", end_time, "ms.")
            print("Opening table with 550 rows took", before - after, "bytes.")
            gc.collect()
            before = gc.mem_free()
            start_time = time.ticks_ms()
        db_table.insert([{"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"}])
        if uC:
            gc.collect()
            after = gc.mem_free()
            end_time = time.ticks_diff(time.ticks_ms(), start_time)
            print("Multi-inserting 28 rows took", end_time, "ms to run.")
            print("Multi-inserting 28 rows took up", before - after, "bytes.")
            gc.collect()
            before = gc.mem_free()
            start_time = time.ticks_ms()
        db_table.insert([{"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"},
                         {"name": "whothere", "password": "******"}])
        if uC:
            gc.collect()
            after = gc.mem_free()
            end_time = time.ticks_diff(time.ticks_ms(), start_time)
            print("Multi-inserting 30 rows took", end_time, "ms to run.")
            print("Multi-inserting 30 rows took up", before - after, "bytes.")
    except Exception:
        return 'Error.'
    else:
        return 'Success.'
예제 #32
0
# Instantiate the XBee device.
xb = xbee.XBee()

# Configure sleep mode to be managed by MicroPython.
xb.atcmd("SM", 0x06)

sleep_time = SLEEP_TIME_MS

# Start reading temperature and humidity measures.
while True:
    # Notify the gateway that the XBee is awake.
    xbee.transmit(xbee.ADDR_COORDINATOR, MSG_AWAKE)
    # Wait during the configured time for incoming messages.
    start_time_ms = time.ticks_ms()
    while time.ticks_diff(time.ticks_ms(), start_time_ms) < AWAKE_TIME_MS:
        incoming = xbee.receive()
        if incoming is not None and incoming[
                "sender_nwk"] == 0 and not incoming["broadcast"]:
            try:
                payload = int(incoming["payload"].decode())
            except ValueError:
                continue
            if payload < 0:
                continue
            # Update the sleep time.
            sleep_time = payload * 1000
            print("Temperature/humidity service stopped.\n" if sleep_time ==
                  0 else "Changed sleep time to %d s.\n" % payload)

    if sleep_time > 0:
예제 #33
0
def wait_ms(sleep_len):
    currentTime = time.ticks_ms()
    while time.ticks_diff(time.ticks_ms(), currentTime) < sleep_len:
        time.sleep_ms(500)
        pass
    return
예제 #34
0
 def millis(self):
     return round(time.ticks_diff(self.t_end, self.t_ini) / 1000, 3)
예제 #35
0
def debug_delta(title=None):
    global debug_timeCounter_last_ms
    if title is not None:
        print(title, time.ticks_diff(time.ticks_ms(),
                                     debug_timeCounter_last_ms), 'ms')
    debug_timeCounter_last_ms = time.ticks_ms()
예제 #36
0
# The Eddystone TLM frame keeps track of the beacon's time alive and advertisement count.
count = 0
start_time = time.ticks_ms()

# A URL to advertise
url = "http://www.digi.com/"

# This is a unique ID given to each beacon, for this example it will be random.
uid = os.urandom(16)

# The TLM frame advertises the beacon's battery voltage if available. It is set to 0 if unavailable.
battery_voltage = 0

while True:
    time_alive = time.ticks_diff(time.ticks_ms(), start_time) / 1000
    beacon_temperature = xbee.atcmd('TP')
    # If the %V command is supported (XBee 3 LTE-M) the following line can be uncommented.
    # battery_voltage = xbee.atcmd('%V') / 1000

    frame = EddystoneTLMFrame(battery_voltage=battery_voltage,
                              beacon_temperature=beacon_temperature,
                              advertisement_count=count,
                              time_sec=time_alive)
    print("Advertising TLM with timestamp: {}seconds\tbattery voltage: {}V\t" \
          "beacon temperature: {}*C\tadvertisement count: {}\n"
          .format(time_alive, battery_voltage, beacon_temperature, count))
    count += advertise_payload_for(frame.get_bytes(),
                                   TIME_BETWEEN_BEACON_TYPES_SEC,
                                   ADVERTISE_INTERVAL_USEC)
예제 #37
0
wlan.connect('my-ap','my-password')

sock_listen = socket.socket()
sock_listen.bind(('0.0.0.0', 9999))
sock_listen.listen(1)

touch0 = machine.TouchPad(machine.Pin(4))
touch2 = machine.TouchPad(machine.Pin(2))
touch4 = machine.TouchPad(machine.Pin(13))
touch5 = machine.TouchPad(machine.Pin(12))
touch6 = machine.TouchPad(machine.Pin(14))
touch7 = machine.TouchPad(machine.Pin(27))

while True:
    try:
        sock, _  = sock_listen.accept()
        start_ticks = time.ticks_ms()
        while True:
            sock.write("%d %d %d %d %d %d %d\n" % (
                time.ticks_diff(time.ticks_ms(), start_ticks),
                touch0.read(),
                touch2.read(),
                touch4.read(),
                touch5.read(),
                touch6.read(),
                touch7.read(),
            ))
            time.sleep(0.01)
    except OSError:
        pass
    pass


ball = Ball(32, 16, 1, 1, 2, -2)
player = Player(30, 31, 10, 1, 0, 0)

y4 = machine.Pin('Y4')
adc = pyb.ADC(y4)
i2c = machine.I2C('X')
fbuf = framebuf.FrameBuffer(bytearray(64 * 32 // 8), 64, 32,
                            framebuf.MONO_HLSB)
tick = time.ticks_ms()

while not game_over:
    ntick = time.ticks_ms()
    ball.update(time.ticks_diff(ntick, tick) // 100, player)
    tick = ntick
    player.x = adc.read() * 58 / 255
    fbuf.fill(0)
    ball.draw(fbuf)
    player.draw(fbuf)
    i2c.writeto(8, fbuf)
    time.sleep_ms(50)  # Adjust this for performance boosts

fbuf.fill(0)
fbuf.text('GAME', 15, 8)
fbuf.text('OVER', 15, 18)
i2c.writeto(8, fbuf)

print('Score: ', score)
예제 #39
0
 def new_func(*args, **kwargs):
     t = time.ticks_us()
     result = f(*args, **kwargs)
     delta = time.ticks_diff(time.ticks_us(), t)
     print('[Time] Function {}: {:6.3f}ms'.format(myname, delta / 1000))
     return result
예제 #40
0
    #neopixel0.setColorFrom(1, 12, 0xFF0000)

    for i in range(10, 180, 10):
        rgb.setColorFrom(1, 12, (R << 16) | (G << 8) | B)
        neopixel0.setColorFrom(1, int(rgb_num / 2), (R << 16) | (G << 8) | B)
        neopixel0.setColorFrom(1 + int(rgb_num / 2), int(rgb_num),
                               (G << 16) | (B << 8) | R)
        #rgb.setColorFrom(1 , 5 ,(R << 16) | (G << 8) | B)
        neopixel0.setBrightness(i)
        rgb.setBrightness(i)
        wait_ms(1)
    for i in range(180, 10, -10):
        rgb.setColorFrom(1, 12, (R << 16) | (G << 8) | B)
        neopixel0.setColorFrom(1, int(rgb_num / 2), (R << 16) | (G << 8) | B)
        neopixel0.setColorFrom(1 + int(rgb_num / 2), int(rgb_num),
                               (G << 16) | (B << 8) | R)
        #rgb.setColorFrom(1 , 5 ,(R << 16) | (G << 8) | B)
        rgb.setBrightness(i)
        neopixel0.setBrightness(i)
        wait_ms(10)

    delta_IIC = time.ticks_diff(time.ticks_ms(),
                                start)  # compute time difference
    label_info1.setText("LED loop time: " + str(delta_IIC) +
                        " ms")  #takes about 2ms
    wait_ms(200)
    run_cnt = run_cnt + 1
    label_cnt.setText("Run: " + str(run_cnt))
    #fade time step
예제 #41
0
        # Since we just set the button_timing value to true, this loop will
        # run. Inside it, if we detect a press of the button, we'll set
        # button_timing to false, stopping this loop.
        while (button_timing):
            # In this while loop, we'll place the sleep time at the beginning
            # Doing so will help "debounce" the switch. For more information on
            # debouncing switches see:
            #  http://docs.micropython.org/en/latest/pyboard/pyboard/tutorial/debounce.html
            time.sleep_ms(100)

            # read the state of the input
            input_state = input_pin.value()

            # Calculate the time elapsed in ms since we first pressed the button
            time_elapsed = time.ticks_diff(time.ticks_ms(), start_time)

            if (input_state):
                GREEN_LED.on()
                RED_LED.off()
                YELLOW_LED.off()
                BLUE_LED.off()
                print("Button pressed to stop.")
                print("Elapsed time = {}ms\n".format(time_elapsed))

                # Set button_timing to False because we are no longer in a
                # timing part of the algorithm. This will break the while loop
                # that is looking for the 2nd press of the button, therefore
                # returning to looking for a first press.
                button_timing = False
예제 #42
0
파일: Main.py 프로젝트: curlyz/Firmware
config_btn = Pin(CONFIG_PIN, Pin.IN)

status_led = NeoPixel(Pin(LED_PIN, Pin.OUT), 1, timing=True)

if config_btn.value():
    print('config button is pressed')
    # turn on config led
    status_led.fill((255, 0, 0))
    status_led.write()

    # start while loop until btn is released
    press_begin = time.ticks_ms()
    press_duration = 0
    while config_btn.value():
        press_end = time.ticks_ms()
        press_duration = time.ticks_diff(press_end, press_begin)
        print(press_duration)
        if press_duration > 2000:
            break
        time.sleep_ms(100)

    # check how long it was pressed
    if press_duration > 2000:
        # if more than 3 seconds => flash led many times and copy original user code file and reset
        print('Config button pressed longer than 3 seconds')
        for i in range(10):
            #status_led.value(1)
            status_led.fill((255, 0, 0))
            status_led.write()
            time.sleep_ms(100)
            #status_led.value(0)
예제 #43
0
import DS1307
from machine import I2C, Pin
from time import sleep, ticks_ms, ticks_diff

i2c = I2C(sda=Pin(21), scl=Pin(22))

with open("timestamp_rtc_ms.txt", mode='r') as rtc_file:
    rtc_readings = rtc_file.read().lstrip('Last reading in millisecond: ')

rtc_readings_last = int(rtc_readings)
print(rtc_readings_last)

rtc_reading_now = ticks_ms()
print(rtc_reading_now)

time_diff = ticks_diff(rtc_reading_now, rtc_readings_last)
print(time_diff)

# Wirte to file
with open("timestamp_rtc_ms.txt", mode='w') as file:
    file.write('Last reading in millisecond: {} \n'.format(rtc_reading_now))
예제 #44
0
spot_test(          1,  (2000,  1,  1,  0,  0,  1, 5,   1))
spot_test(         59,  (2000,  1,  1,  0,  0, 59, 5,   1))
spot_test(         60,  (2000,  1,  1,  0,  1,  0, 5,   1))
spot_test(       3599,  (2000,  1,  1,  0, 59, 59, 5,   1))
spot_test(       3600,  (2000,  1,  1,  1,  0,  0, 5,   1))
spot_test(         -1,  (1999, 12, 31, 23, 59, 59, 4, 365))
spot_test(  447549467,  (2014,  3,  7, 23, 17, 47, 4,  66))
spot_test( -940984933,  (1970,  3,  7, 23, 17, 47, 5,  66))
spot_test(-1072915199,  (1966,  1,  1,  0,  0,  1, 5,   1))
spot_test(-1072915200,  (1966,  1,  1,  0,  0,  0, 5,   1))
spot_test(-1072915201,  (1965, 12, 31, 23, 59, 59, 4, 365))

t1 = time.time()
time.sleep(2)
t2 = time.time()
print(abs(time.ticks_diff(t1, t2) -2) <= 1)

t1 = time.ticks_ms()
time.sleep_ms(50)
t2 = time.ticks_ms()
print(abs(time.ticks_diff(t1, t2)- 50) <= 1)

t1 = time.ticks_us()
time.sleep_us(1000)
t2 = time.ticks_us()
print(time.ticks_diff(t1, t2) < 2000)

t1 = time.ticks_cpu()
t2 = time.ticks_cpu()
print(time.ticks_diff(t1, t2) >= 0)
예제 #45
0
    def get_request(self, unit_addr_list=None, timeout=None):
        if self._sock == None:
            raise Exception('Modbus TCP server not bound')

        start_ms = time.ticks_ms()
        while True:
            elapsed = time.ticks_diff(start_ms, time.ticks_ms())
            if elapsed > timeout:
                return None

            if self._client_sock == None:
                accept_timeout = None if timeout == None else (timeout - elapsed) / 1000
            else:
                accept_timeout = 0
            self._sock.settimeout(accept_timeout)

            new_client_sock = None
            try:
                new_client_sock, client_address = self._sock.accept()
            except OSError as e:
                if e.args[0] != 11: # 11 = timeout expired
                    raise e

            if new_client_sock != None:
                if self._client_sock != None:
                    self._client_sock.close()
                self._client_sock = new_client_sock
                self._client_sock.settimeout(0.2) # recv() timeout

            if self._client_sock != None:
                try:
                    req = self._client_sock.recv(256)
                    if len(req) == 0:
                        # connection terminated
                        self._client_sock.close()
                        self._client_sock = None
                        continue

                    req_header_no_uid = req[:Const.MBAP_HDR_LENGTH - 1]
                    self._req_tid, req_pid, req_len = struct.unpack('>HHH', req_header_no_uid)
                    req_uid_and_pdu = req[Const.MBAP_HDR_LENGTH - 1:Const.MBAP_HDR_LENGTH + req_len - 1]

                except TimeoutError:
                    continue
                except Exception as e:
                    print("Modbus request error:", e)
                    self._client_sock.close()
                    self._client_sock = None
                    continue

                if (req_pid != 0):
                    print("Modbus request error: PID not 0")
                    self._client_sock.close()
                    self._client_sock = None
                    continue

                if unit_addr_list != None and req_uid_and_pdu[0] not in unit_addr_list:
                    continue

                try:
                    return Request(self, req_uid_and_pdu)
                except ModbusException as e:
                    self.send_exception_response(req[0], e.function_code, e.exception_code)
예제 #46
0
파일: BlynkLib.py 프로젝트: seco/wipy
def sleep_from_until(start, delay):
    while time.ticks_diff(start, time.ticks_ms()) < delay:
        machine.idle()
    return start + delay
예제 #47
0
def run_until_complete(main_task=None):
    global cur_task
    excs_all = (CancelledError, Exception
                )  # To prevent heap allocation in loop
    excs_stop = (CancelledError, StopIteration
                 )  # To prevent heap allocation in loop
    while True:
        # Wait until the head of _task_queue is ready to run
        dt = 1
        while dt > 0:
            dt = -1
            t = _task_queue.peek()
            if t:
                # A task waiting on _task_queue; "ph_key" is time to schedule task at
                dt = max(0, ticks_diff(t.ph_key, ticks()))
            elif not _io_queue.map:
                # No tasks can be woken so finished running
                return
            # print('(poll {})'.format(dt), len(_io_queue.map))
            _io_queue.wait_io_event(dt)

        # Get next task to run and continue it
        t = _task_queue.pop_head()
        cur_task = t
        try:
            # Continue running the coroutine, it's responsible for rescheduling itself
            exc = t.data
            if not exc:
                t.coro.send(None)
            else:
                # If the task is finished and on the run queue and gets here, then it
                # had an exception and was not await'ed on.  Throwing into it now will
                # raise StopIteration and the code below will catch this and run the
                # call_exception_handler function.
                t.data = None
                t.coro.throw(exc)
        except excs_all as er:
            # Check the task is not on any event queue
            assert t.data is None
            # This task is done, check if it's the main task and then loop should stop
            if t is main_task:
                if isinstance(er, StopIteration):
                    return er.value
                raise er
            if t.state:
                # Task was running but is now finished.
                waiting = False
                if t.state is True:
                    # "None" indicates that the task is complete and not await'ed on (yet).
                    t.state = None
                else:
                    # Schedule any other tasks waiting on the completion of this task.
                    while t.state.peek():
                        _task_queue.push_head(t.state.pop_head())
                        waiting = True
                    # "False" indicates that the task is complete and has been await'ed on.
                    t.state = False
                if not waiting and not isinstance(er, excs_stop):
                    # An exception ended this detached task, so queue it for later
                    # execution to handle the uncaught exception if no other task retrieves
                    # the exception in the meantime (this is handled by Task.throw).
                    _task_queue.push_head(t)
                # Save return value of coro to pass up to caller.
                t.data = er
            elif t.state is None:
                # Task is already finished and nothing await'ed on the task,
                # so call the exception handler.
                _exc_context["exception"] = exc
                _exc_context["future"] = t
                Loop.call_exception_handler(_exc_context)
예제 #48
0

############################################################
#
# Start script execution ...
#
############################################################
# Setup the MCU and application code to starting conditions
# The blue LED will start on, the yellow LED will be off
pyb.LED(LED_BLUE).on()
pyb.LED(LED_GREEN).off()

# Create task timer for Blue LED
TimerBlueLed = pyb.Timer(1)
TimerBlueLed.init(freq=5)
TimerBlueLed.callback(task1)
print("Task 1 - Blue LED Toggle initialized ...")

# Create task timer for Green LED
TimerGreenLed = pyb.Timer(2)
TimerGreenLed.init(freq=5)
TimerGreenLed.callback(task2)
print("Task 2 - Green LED Toggle initialized ...")

# Tracks seconds since program started
TimeStart = time.ticks_ms()

while True:
    time.sleep_ms(5000)
    SecondsLive = time.ticks_diff(time.ticks_ms(), TimeStart) / 1000
    print("Executing for ", SecondsLive, " seconds")
 def read(self):
     """ """
     import time
     return time.ticks_diff(time.ticks_ms(), self.start) / 1000.0
예제 #50
0
 def _cb_edge(self, x):
     # Only count the edge if spaced by 0.12ms (switch debounce)
     if time.ticks_diff(time.ticks_ms(), self.last_trigger) > 0.12:
         self.callback_edge(x)
         self.t = time.ticks_ms()
         gc.collect()
예제 #51
0
from mqtt_manager import MQTT_Manager  # MQTT Connection
mqtt_client = MQTT_Manager()
mqtt_client.check()  # Open connection to broker
TOPIC_SUB = mqtt_client.get_topic('control')
TOPIC_PUB = mqtt_client.get_topic('status')


def mqtt_callback(topic, msg):
    print('MSG! Topic:{}; Data{}'.format(topic, msg))


mqtt_client.broker.set_callback(mqtt_callback)
mqtt_client.broker.subscribe(TOPIC_SUB)

# Change this to your sensor
from board_manager import D1
from sensor_manager import Sensor_DS18B20
sensor = Sensor_DS18B20(D1)  # Pin 5 = D1

DELAY = 5 * 1000  # DELAY in milliseconds
while True:
    sensor.read()
    msg = sensor.values_dict
    print(msg)
    mqtt_client.send(TOPIC_PUB, json.dumps(msg))
    t_start = time.ticks_ms()
    while time.ticks_diff(time.ticks_ms(), t_start) <= DELAY:
        mqtt_client.check_msg()  # check for new messages
        time.sleep_ms(200)
#End main loop