def run(bios): thread = bios send_value = None call_stack.append(bios) while call_stack: print('[%i] %s(%r)' % (len(call_stack), thread.name, send_value)) status, result = thread(send_value) next_thread = None if status != STATUS_PAUSE: print('[+]', '%s -> %s: %s' % (thread.name, status, result)) if status == STATUS_PAUSE: next_thread, send_value = result elif status == STATUS_EXCEPTION: print("=" * 5, "exception on", thread.name, "=" * 5) sys.print_exception(result) print("=" * 20) call_stack.pop() send_value = None elif status == STATUS_STOP: call_stack.pop() send_value = None else: send_value = None if next_thread is None: next_thread = bios thread = next_thread utime.sleep(0.05)
def main(quit=True): global t c = MQTTClient(CLIENT_ID, SERVER) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC, qos = QOS) print("Connected to %s, subscribed to %s topic" % (SERVER, TOPIC)) n = 0 pubs = 0 try: while 1: n += 1 if not n % 100: t = ticks_ms() c.publish(TOPIC, str(pubs).encode('UTF8'), retain = False, qos = QOS) c.wait_msg() pubs += 1 if not pubs % 100: print('echo received in max {} ms min {} ms'. format(maxt, mint)) if quit: return sleep(0.05) c.check_msg() finally: c.disconnect()
def dual(use_spi=False, soft=True): ssd0 = setup(False, soft) # I2C display ssd1 = setup(True, False) # SPI instance Writer.set_textpos(ssd0, 0, 0) # In case previous tests have altered it wri0 = Writer(ssd0, small, verbose=False) wri0.set_clip(False, False, False) Writer.set_textpos(ssd1, 0, 0) # In case previous tests have altered it wri1 = Writer(ssd1, small, verbose=False) wri1.set_clip(False, False, False) nfields = [] dy = small.height() + 6 col = 15 for n, wri in enumerate((wri0, wri1)): nfields.append([]) y = 2 for txt in ('X:', 'Y:', 'Z:'): Label(wri, y, 0, txt) nfields[n].append(Label(wri, y, col, wri.stringlen('99.99'), True)) y += dy for _ in range(10): for n, wri in enumerate((wri0, wri1)): for field in nfields[n]: value = int.from_bytes(uos.urandom(3),'little')/167772 field.value('{:5.2f}'.format(value)) wri.device.show() utime.sleep(1) for wri in (wri0, wri1): Label(wri, 0, 64, ' DONE ', True) wri.device.show()
def calibrate(self, getxyz, stopfunc, wait=0): magmax = list(getxyz()) # Initialise max and min lists with current values magmin = magmax[:] while not stopfunc(): if wait != 0: if callable(wait): wait() else: time.sleep(wait/1000) # Portable magxyz = tuple(getxyz()) for x in range(3): magmax[x] = max(magmax[x], magxyz[x]) magmin[x] = min(magmin[x], magxyz[x]) self.magbias = tuple(map(lambda a, b: (a +b)/2, magmin, magmax))
def check_home(): sta_if = network.WLAN(network.STA_IF) sta_if.active(True) while(1): found = False ssids = sta_if.scan() for ssid in ssids: if ssid[0].decode('utf8') == WIFI_SSID_HOME: show1(True) found = True break if not found: show1(False) utime.sleep(5)
def init_sta(status): import utime if status == True: wlan.active(True) count = 0 if not wlan.isconnected(): # should connect... wlan.connect(sta_ssid, sta_password) # if not then explicitly call connect while not wlan.isconnected(): # try connecting for 10 seconds print("Waiting for IP... Count:", count) if count == 10: print ("Can't find wifi - resetting") sleep.init(sleep_interval) # pass an argument to delay awakening? utime.sleep(1) count +=1 print('Network Configuration:', wlan.ifconfig()) else: wlan.active(False)
def usd_scroll(use_spi=False, soft=True): ssd = setup(use_spi, soft) # Create a display instance # Only CWriter can do usd CWriter.invert_display(ssd) CWriter.set_textpos(ssd, 0, 0) wri = CWriter(ssd, freesans20, verbose=False) wri.set_clip(False, False, False) # Char wrap wri.printstring('Sunday\n') wri.printstring('12 Aug 2018\n') wri.printstring('10.30am') for x in range(5): ssd.show() utime.sleep(2) wri.printstring('\nCount = {:2d}'.format(x)) ssd.show() utime.sleep(2) wri.printstring('\nDone.') ssd.show() CWriter.invert_display(ssd, False) # For subsequent tests
def scroll(use_spi=False, soft=True): ssd = setup(use_spi, soft) # Create a display instance rhs = WIDTH -1 ssd.line(rhs - 20, 0, rhs, 20, 1) square_side = 10 ssd.fill_rect(rhs - square_side, 0, square_side, square_side, 1) Writer.set_textpos(ssd, 0, 0) # In case previous tests have altered it wri = Writer(ssd, freesans20, verbose=False) wri.set_clip(False, False, False) # Char wrap wri.printstring('Sunday\n') wri.printstring('12 Aug 2018\n') wri.printstring('10.30am') for x in range(5): ssd.show() utime.sleep(2) wri.printstring('\nCount = {:2d}'.format(x)) ssd.show() utime.sleep(2) wri.printstring('\nDone.') ssd.show()
def upload_loop(self): #print("upload_loop") while True: sleep_time = self.upload_data() time.sleep(sleep_time)
import machine import utime button = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_DOWN) led_external = machine.Pin(15, machine.Pin.OUT) while True: led_external.value(0) if button.value() == 1: print("Button Pressed!") led_external.value(1) utime.sleep(.5)
import _thread import micropython micropython.alloc_emergency_exception_buf(100) # Init objects screen = Display() screen.print("TubaLux(tm)") # Read conf try: conffile = uio.open("config", 'r') config = ujson.loads(conffile.read()) conffile.close() except OSError: screen.print("No conf file") sleep(1) import sys sys.exit() prog = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP) if (prog.value() == 0): screen.print("Programming mode") sleep(1) import sys sys.exit() try: rings = config["rings"] except KeyError: rings = None leds = Led(screen, config["num_leds"], config["led_pin"], rings if rings else None)
PIN_LED_G = 72 # PE8 PIN_LED_B = 73 # PE9 LED_ON = 0 LED_OFF = 1 led_r = Pin(("LED RED", PIN_LED_R), Pin.OUT_PP) led_g = Pin(("LED GREEN", PIN_LED_G), Pin.OUT_PP) led_b = Pin(("LED BLUE", PIN_LED_B), Pin.OUT_PP) blink_tab = [(LED_ON, LED_ON, LED_ON), (LED_OFF, LED_ON, LED_ON), (LED_ON, LED_OFF, LED_ON), (LED_ON, LED_ON, LED_OFF), (LED_OFF, LED_OFF, LED_ON), (LED_ON, LED_OFF, LED_OFF), (LED_OFF, LED_ON, LED_OFF), (LED_ON, LED_OFF, LED_OFF)] count = 0 while True: group_num = count % len(blink_tab) led_r.value(blink_tab[group_num][0]) # set led status led_g.value(blink_tab[group_num][1]) led_b.value(blink_tab[group_num][2]) count += 1 time.sleep(0.5)
def reset(self): if self.rst is not None: self.rst.value(0) utime.sleep(0.1) self.rst.value(1)
leds.set(l, urandom.choice(COLORS)) bg = LineDrawer() fgs = [NoneDrawer(), NickDrawer(), TimeDrawer()] fg_no = 0 leds_on = False while True: pressed = buttons.read(buttons.BOTTOM_LEFT | buttons.BOTTOM_RIGHT | buttons.TOP_RIGHT) if pressed & buttons.BOTTOM_LEFT != 0: fg_no = fg_no - 1 if fg_no > 0 else len(fgs) - 1 elif pressed & buttons.BOTTOM_RIGHT != 0: fg_no = fg_no + 1 if fg_no < len(fgs) - 1 else 0 elif pressed & buttons.TOP_RIGHT != 0: leds_on = not leds_on if not leds_on: leds.clear() with display.open() as disp: disp.clear() bg.draw(disp) fgs[fg_no].draw(disp) disp.update() if leds_on: matrix_leds() utime.sleep(DELAY_SEC)
def sontek_pressure(arg): utime.sleep( .02 ) #prevent all 3 measurements from triggering at once if they are scheduled at the same time. Allow temp to complete before getting data. get_data() return (pressure)
import ustruct
pi = pressure // 100 pd = pressure - pi * 100 hi = humidity // 1024 hd = humidity * 100 // 1024 - hi * 10 payload = dict(temperature=temperature / 100, humidity="{}.{:02d}".format(hi, hd), pressure="{}.{:02d}".format(pi, pd)) topic = "/pieter-room/sensor" message = bytes(json.dumps(payload), "utf-8") client = MQTTClient(client_id=client_id, server="10.0.1.200", user="******", password="******") client.connect() client.publish(topic=topic, msg=message) client.disconnect() except Exception as ex: print(ex) utime.sleep(300)
lasthour = None while True: year = str(rtc.datetime()[0]) month = str(rtc.datetime()[1]) if len(month) == 1: month = '0' + month day = str(rtc.datetime()[2]) if len(day) == 1: day = '0' + day hour = str(rtc.datetime()[4]) if len(hour) == 1: hour = '0' + hour minute = str(rtc.datetime()[5]) if len(minute) == 1: minute = '0' + minute second = str(rtc.datetime()[6]) if len(second) == 1: second = '0' + second date = day + '/' + month + '/' + year if not hour == lasthour: weekday = DAYS[rtc.datetime()[3]] blk() oled.text(weekday, 20, 1) oled.text(date, 20, 20) oled.show() lasthour = hour mydisplay.numbers(int(hour), int(minute)) sleep(1)
def parpadeo(luz): for veces in range(luz): led_int(1) utime.sleep(.1) led_int(0) utime.sleep(.1)
def parpadeo(luz): for veces in range(luz): led_int(1) utime.sleep(.1) led_int(0) utime.sleep(.1) reg_temp = open('datos.txt', 'a') reg_temp.write('Hito ' + ';' + 'Temperatura' + '\n') reg_temp.close() factor = 3.3 / (65535) utime.sleep(.2) parpadeo(5) reg_temp = open('datos.txt', 'a') comienzo = utime.ticks_ms() while True: lectura = temp_int.read_u16() * factor hito = round(((utime.ticks_ms() - comienzo) / 1000), 1) tempC = round((27 - (lectura - 0.706) / 0.001721), 1) reg_temp.write(str(hito) + '; ' + str(tempC) + '\n') reg_temp.flush() parpadeo(2) utime.sleep(5)
def sontek_Velocity_east_depth_1(arg): utime.sleep( .04 ) #prevent all 3 measurements from triggering at once if they are scheduled at the same time. Allow temp to complete before getting data. get_data() return (velocity_east)
try: import utime as time except: import time from apq8016_gpio import Pin led1 = Pin(21) switch3 = Pin(107) # Light LED when on-board button S3 is pressed while 1: # Inverted input led1.value(not switch3.value()) # Don't burn CPU time.sleep(0.01)
g.run() # MQTT init clientid = "{imei}_1" pw = "" iccid = "" mqttServer = "220.180.239.212" c = MqttClient(clientid, mqttServer, 8420, pw) c.connect() sub_topic = "quec/{imei}/down" pub_topic = "quec/{imei}/up" c.subscribe(sub_topic) c.start() while 1: utime.sleep(3) if (TEMPERATUR != None) and (HUMIDITY != None) and (LIGHT != None) and (GPSMSG != []): if GPSMSG[3] != "": print("T", TEMPERATUR) print("H", HUMIDITY) print("L", LIGHT) print("G", GPSMSG) try: data = TrackerMsgFormat(TEMPERATUR, HUMIDITY, LIGHT, GPSMSG, iccid) c.publish(pub_topic, data) # 发布到云端 except: continue else: print("Get the GPS data") else: print("Get the GPS data")
probe, 'fail', webPageResult[2]) except Exception as e: sys.print_exception(e) # 2 **************** Governor & probeConfig refresh *************************** gc.collect() print("governorSeconds: ", str(probeConfig['governorSeconds']), " memory:", umemory.free()) # print("loop time so far:", utime.time() - loopStartTime) probeConfig = mqttProcessConfigAndMeasurements() sleeper = probeConfig['governorSeconds'] - \ (utime.time() - loopStartTime) print("Sleeping time remaining: ", sleeper) if (sleeper > 0): utime.sleep(sleeper) probeConfig = mqttProcessConfigAndMeasurements() # Clean up network connection (Not needed when used in a real main.py that never ends) print('disconnecting from network...') net_if.active(False) while net_if.isconnected(): pass print('Disconnected from network') except Exception as e: sys.print_exception(e) print("Waiting 60 seconds to reboot...") utime.sleep(60) print('Reboot') machine.reset()
# Input a value 0 to 255 to get a color value. # The colours are a transition r - g - b - back to r. if pos < 0 or pos > 255: return (0, 0, 0) if pos < 85: return (255 - pos * 3, pos * 3, 0) if pos < 170: pos -= 85 return (0, 255 - pos * 3, pos * 3) pos -= 170 return (pos * 3, 0, 255 - pos * 3) def rainbow_cycle(wait): for j in range(255): for i in range(num_pixels): rc_index = (i * 256 // num_pixels) + j pixels[i] = wheel(rc_index & 255) pixels.write() counter = 0 while True: for i in range(0, NUMBER_PIXELS): # print(wheel(counter)) strip.set_pixel(i, wheel(counter)) strip.show() counter += 1 counter = counter % 255 sleep(.01)
if __name__ == "__main__": from machine import Pin, SPI spi = SPI(0,baudrate=10000000,sck=Pin(6),mosi=Pin(7)) dc=Pin(2,Pin.OUT) cs=Pin(3,Pin.OUT) oled = SSD1331(spi=spi,dc=Pin(2),cs=Pin(3)) oled.fill(0) import framebuf buffer = bytearray(oled.width * oled.height * 2) fb = framebuf.FrameBuffer(buffer, oled.width, oled.height, framebuf.RGB565) #test frame buffer colors = [] for i in range(8): r = (i & 1) * 255 g = ((i >> 1) & 1) * 255 b = ((i >> 2) & 1 ) * 255 colors.append(oled.color565(r,g,b)) while True: for color in colors: fb.fill(color) oled.block(0,0,96,64,buffer) utime.sleep(1)
def main(): temp = float('NaN') hum = float('NaN') t = {} blink_led1() OLED.fill(0) # 0: black, 1: white while True: try: DHT.measure() temp = DHT.temperature() hum = DHT.humidity() except Exception as e: #blink_led1() print("Error in main loop: {}".format(str(e))) if not isnan(temp) and not isnan(hum): topic = "metrics/temperature/casa/{}".format(SECRETS['sensor']['name'].lower()) msg = "{{\"name\":\"{}\",\"type\":\"temperature\",\"value\":{:.2f}}}" \ .format(SENSOR_ID, temp) topic2 = "metrics/humidity/casa/{}".format(SECRETS['sensor']['name'].lower()) msg2 = "{{\"name\":\"{}\",\"type\":\"humidity\",\"value\":{:.2f}}}" \ .format(SENSOR_ID, hum) try: if connect(): if client.connect() == 0: client.publish(topic=topic, msg=msg, qos=1) print("Published {} on topic {}".format(msg, topic)) client.publish(topic=topic2, msg=msg2, qos=1) print("Published {} on topic {}".format(msg2, topic2)) client.disconnect() try: t = ext_temp() except Exception as e: # blink_led1(iterations=2) print("Error while getting ext temperature: {}".format(str(e))) except Exception as e: # blink_led1(iterations=3) print("Error while connecting and sending message: {}".format(str(e))) disconnect() for i in range(6): if not isnan(temp): update_main_area("{:.1f}ºC".format(temp)) if not isnan(hum): update_bottom_area("{:.1f}% ".format(hum)) utime.sleep(SLEEP_TIME_2) if 'temp' in t: update_bottom_area("ext: {:.1f}ºC ".format(t['temp'])) utime.sleep(SLEEP_TIME_1) if 'ts' in t: update_bottom_area("{}/{} {}:{} ".format(t['ts'][2], t['ts'][1], t['ts'][3], t['ts'][4])) utime.sleep(SLEEP_TIME_2)
''' Device: LEGO SPIKE Prime Summary: This code reads the slider potentiometer value from Grove Pyboard backpack and runs the motor with corresponding speeds Tufts Center for Engineering Education and Outreach Updated on: 01/07/2020 ''' import hub, utime hub.port.B.info() # if info comes back with None - then you have to restart the Grove Pyboard backpack #Set mode to Int16 hub.port.B.device.mode(1) while True: try: value = hub.port.B.device.get()[0] print(value) #Convert the values between range 0 to 4000 to 0 to 90 value = 2 * (value / 100) hub.port.A.motor.pwm(int(value)) # powers motor from 0 - 90 utime.sleep(0.2) except: utime.sleep(0.2) print("Not Connected")
zeile1 = [1, 2, 2, 1, 1, 1, 1, 1, 2, 2, 1] zeile2 = [2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2] feld = [ zeile1, zeile2, [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], [2, 2, 3, 3, 3, 3, 3, 3, 3, 2, 2], [2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2], [2, 3, 4, 3, 3, 3, 3, 3, 4, 3, 2], [2, 3, 3, 3, 4, 3, 4, 3, 3, 3, 2], [2, 2, 3, 3, 4, 4, 4, 3, 3, 2, 2], [1, 2, 2, 3, 3, 3, 3, 3, 2, 2, 1], [1, 1, 2, 2, 2, 2, 2, 2, 2, 1, 1], ] while True: for zeilenindex, zeile in enumerate(feld): for lama, colorcode in enumerate(zeile): if 1 == colorcode: leds.prep(lama, htmlcolor.RED) if 2 == colorcode: leds.prep(lama, htmlcolor.BLUE) if 3 == colorcode: leds.prep(lama, htmlcolor.WHITE) if 4 == colorcode: leds.prep(lama, htmlcolor.BLACK) leds.update() utime.sleep(0.004)
import utime as time from machine import Pin import dht import BlynkLib WIFI_SSID = 'yourWifiID' WIFI_PASS = '******' BLYNK_AUTH = 'yourAuth' GPIO_DHT22_PIN = 4 print("Connecting to WiFi network '{}'".format(WIFI_SSID)) wifi = network.WLAN(network.STA_IF) wifi.active(True) wifi.connect(WIFI_SSID, WIFI_PASS) while not wifi.isconnected(): time.sleep(1) print('WiFi connect retry ...') print('WiFi IP:', wifi.ifconfig()[0]) print("Connecting to Blynk server...") blynk = BlynkLib.Blynk(BLYNK_AUTH) T_VPIN = 3 H_VPIN = 4 dht22 = dht.DHT22(machine.Pin(GPIO_DHT22_PIN)) while True: try: time.sleep(2)
from machine import Pin from utime import sleep led = Pin(25, Pin.OUT) def blink(times, delay): for x in range(1, times+1): led.on() sleep(delay) led.off() sleep(delay) while True: blink(3, 0.2) sleep(0.4) blink(3, 0.6)
sensor.measure() t = sensor.temperature() h = sensor.humidity() return t, h def read_dht22(self, pin): sensor = dht.DHT22(machine.Pin(pin)) while True: utime.sleep(2) sensor.measure() t = sensor.temperature() h = sensor.humidity() return t, h if __name__ == '__main__': my_dhtxx = dhtxx_wemos_mini() while True: dht11_pin = 15 t, h = my_dhtxx.read_dht11(dht11_pin) print('DHT11 pin:' + str(dht11_pin), 'Temperature: %3.1f°C' % t, 'Humidity: %3.0f%%' % h) dht22_pin = 16 t, h = my_dhtxx.read_dht22(dht22_pin) print('DHT22 pin:' + str(dht22_pin), 'Temperature: %3.1f°C' % t, 'Humidity: %3.0f%%' % h) print() utime.sleep(5)
import utime from machine import Timer t1 = Timer(0, 10) t2 = Timer(1, 3) t1.callback(lambda t: print(t, "tick1")) t2.callback(lambda t: print(t, "tick2")) utime.sleep(3) print("done")
if is_micropython: def TimeDiff(start, end): return time.ticks_diff(start, end)/1000000 else: # Cpython cheat: test data does not roll over def TimeDiff(start, end): return (start - end)/1000000 # Expect a timestamp. Use supplied differencing function. fuse = Fusion(TimeDiff) def getmag(): # Return (x, y, z) magnetometer vector. imudata = next(get_data) return imudata[2] print(intro) fuse.calibrate(getmag, lambda : not calibrate, lambda : time.sleep(0.01)) print('Cal done. Magnetometer bias vector:', fuse.magbias) print('Heading Pitch Roll') count = 0 while True: try: data = next(get_data) except StopIteration: # A file is finite. break # A real app would probably run forever. fuse.update(*data) if count % 25 == 0: print("{:8.3f} {:8.3f} {:8.3f}".format(fuse.heading, fuse.pitch, fuse.roll)) time.sleep(0.02) count += 1
import umqtt3 as mqtt import utime as time # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): #print(msg.topic+" "+str(msg.payload)) print('new'+msg['topic']+str(msg['payload'])) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("54.173.234.69", 1883, 60) while 1: client.loop() print(time.time()) time.sleep(4)
# while True: # test() counter = 0 while True: distance = ping() # skip over large numbers while distance > 100: distance = ping() print(distance) if distance < TURN_DISTANCE: print('Reverseing') reverse() sleep(BACKUP_TIME) stop() sleep(.5) print('Turning') if randint(0, 2): # 50% chance of being true turn_right() else: turn_left() sleep(TURN_TIME) stop() sleep(.5) else: print('Forward') forward() sleep(.5)
import led.de0led as led import utime as ut leds = [led.LED(i) for i in range(0, 8)] for i in range(0, 16): leds[i % 8].toggle() ut.sleep(0.5)
def _wait_for_reading(self, additional=0): basetime = 0.018 if (self.mode & 0x03) == 0x03 else 0.132 # 0.128 sleep(basetime * (self._sensitivity/69.0) + additional)
key = bytearray(256 // 8) iv = bytearray(16) data = bytearray(128) # from now on we don't use the heap for loop in range(5): # encrypt aes.set_key(key) aes.set_iv(iv) for i in range(8): aes.apply_to(data) # decrypt aes.set_key(key) aes.set_iv(iv) for i in range(8): aes.apply_to(data) # verify for i in range(len(data)): assert data[i] == 0 count.add(1) if __name__ == '__main__': n_thread = 20 for i in range(n_thread): _thread.start_new_thread(thread_entry, ()) while count.value < n_thread: time.sleep(1)
def blink(times, delay): for x in range(1, times+1): led.on() sleep(delay) led.off() sleep(delay)
import network import ubinascii import utime from machine import Pin p1 = Pin(15, Pin.OUT) p2 = Pin(13, Pin.OUT) led = cm.LED(2) led.blink(5) credentials = cm.get_attributes('credentials.txt') utime.sleep(.5) led.blink(2) ap_if = network.WLAN(network.AP_IF) utime.sleep(.5) led.blink(3) net = cm.connect() utime.sleep(.5) led.blink(4) mac = ubinascii.hexlify(network.WLAN().config('mac'), ':').decode() utime.sleep(.5) led.blink(5) print('mac')
try: import utime as time except: import time from apq8016_gpio import Pin led1 = Pin(21) while 1: led1.value(1) time.sleep(0.5) led1.value(0) time.sleep(0.5)
def run_timer(self, secs): self.message_send( "[INFO] Timer Initialised, callback will be ran every %s seconds!!!" % secs, True, ) self.water_pump.pump_off() while True: self.soil_sensor_check() while self._water_me: self.message_send("*" * 80) self.message_send( "[INFO] Note: Automatically watering the plant(s):\t %s" % current_time(), True, ) # This is brutal: Refactor if not self.water_pump.pump_status: self.message_send( "Turning Pump On: \t %s" % current_time(), True) self.water_pump.pump_on() self.message_send( "[DEBUG] Setting Pump ON as water is @ %.2f%%" % self._soilmoistperc, True, ) utime.sleep(self.config["water_pump_time"].get( "delay_pump_on", 1)) self.message_send( "Turning Pump Off: \t %s" % current_time(), True) self.water_pump.pump_off() if self.water_pump.pump_status: self.message_send( "[FATAL] Could not switch Pump off, resetting device.", True) machine.reset() self.message_send( "[DEBUG] Wait for few seconds for soil to soak", True) utime.sleep(10) self.message_send( "[DEBUG] Checking Soil Moisture Status...", True) # TODO: Improve this logic for i in range(5): self.soil_sensor_check(n_samples=5, rate=2) utime.sleep(60) self.water_pump.pump_off() self.message_send( "[DEBUG] Soil Moisture Percent @ %.2f%%" % self._soilmoistperc, True, ) if self.water_pump.pump_status: self.water_pump.pump_off() self.message_send( "[DEBUG] Setting Pump OFF as water is @ %.2f%%" % self._soilmoistperc, True, ) print("[DEBUG] Sleep for %s seconds" % secs) utime.sleep(secs)
import utime from machine import I2C, Pin, UART, unique_id import neopixel, machine id = unique_id() chipId='{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}'.format(id[0], id[1], id[2], id[3], id[4], id[5]) print('chipId shows: ', chipId) i2c = machine.I2C(scl=Pin(22), sda=Pin(21)) print('i2c bus shows: ', i2c.scan()) uart2=UART(1,rx=26,tx=27,baudrate=9600) uart1=UART(2,rx=0,tx=2,baudrate=9600) utime.sleep(2) print('uart1 shows:', uart1.read(32)) print('uart2 shows:', uart2.read(32)) RED = (255,0,0); GREEN = (0,255,0); BLUE = (0,0,255) colors = [RED, GREEN, BLUE] np = neopixel.NeoPixel(Pin(12), 1) for color in colors: np[0] = color np.write() utime.sleep(1)
tx=17, rx=16, timeout=100) #imu = BNO055(serial=ser) calibrated = False machine.freq(240000000) print('CPU Speed: ' + str(machine.freq())) sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect("Tomato24", "Stephen123") print("Waiting for connection...") while not sta_if.isconnected(): utime.sleep(1) print(sta_if.ifconfig()) utime.sleep(5) s = usocket.socket() addr = usocket.getaddrinfo('192.168.1.112', 61111, 0, usocket.SOCK_STREAM)[0][-1] quat = bytes(8) while True: utime.sleep_ms(5) #time.sleep(1) # if not calibrated: # calibrated = imu.calibrated() # print('Calibration required: sys {} gyro {} accel {} mag {}'.format(*imu.cal_status()))
def delay(self, i): utime.sleep(self.DELAY)
def delay_ms(self, delaytime): utime.sleep(delaytime / 1000.0)
def wait(self, delay): # Default wait implementation, to be overriden in subclasses # with IO scheduling log.debug("Sleeping for: %s", delay) time.sleep(delay)
from arlorobot import * import utime bot = ArloRobot() print("Reseteando encoder...") bot.clear_counts() print("Posiciones efectuadas por motor derecho: ", bot.read_right_counts()) bot.move(0, 100, 200) utime.sleep(4) print("Posiciones efectuadas por motor derecho: ", bot.read_right_counts()) bot.move(0, 50, 200) utime.sleep(4) print("Posiciones efectuadas por motor derecho: ", bot.read_right_counts()) bot.move(0, -150, 200) utime.sleep(4) print("Posiciones efectuadas por motor derecho: ", bot.read_right_counts()) bot.move(0, -200, 200) utime.sleep(4) print("Posiciones efectuadas por motor derecho: ", bot.read_right_counts()) bot.move(0, -200, 200) utime.sleep(4) print("Posiciones efectuadas por motor derecho: ", bot.read_right_counts())