def setup(): dt = pyb.RTC().datetime() if (dt[0] == 2014) and (dt[1] == 1): pyb.RTC().datetime( (inputint("Year [yyyy]: ", 2014, 3000), inputint("Month [1..12]: ", 1, 12), inputint("Day of month [1..31]: ", 1, 31), inputint("Day of week [1 = Monday]: ", 1, 7), inputint("Hour [0..23]: ", 0, 23), inputint("Minute [0..59]: ", 0, 59), 0, 0)) dt = pyb.RTC().datetime() print('RTC: {:04},{:02},{:02} {:02}:{:02}'.format(dt[0], dt[1], dt[2], dt[4], dt[5]))
def sync_rtc(self): """Synchronizes rtc with gps data.""" if self.is_valid_gprmc(): utils.log_file("{} => syncyng rtc...".format(self.name), constants.LOG_LEVEL) utc_time = self.sentence[1] utc_date = self.sentence[9] rtc = pyb.RTC() try: rtc.datetime( (int("20" + utc_date[4:6]), int(utc_date[2:4]), int(utc_date[0:2]), 0, int(utc_time[0:2]), int(utc_time[2:4]), int(utc_time[4:6]), float(utc_time[6:]) )) # rtc.datetime(yyyy, mm, dd, 0, hh, ii, ss, sss) utils.log_file( "{} => rtc successfully synchronized (UTC: {})".format( self.name, utils.time_string(utime.time())), constants.LOG_LEVEL) except: utils.log_file( "{} => unable to synchronize rtc".format( self.name, utils.time_string(utime.time())), constants.LOG_LEVEL) return
def __init__(self): print( "ExiTrak.init" ) # Used for debugging: prints statement when the method is called # self.led = pyb.LED(1) # self.sw = pyb.Switch() # self.PIN_ON = 1 self.rtc = pyb.RTC( ) # Instantiates the Real Time Clock Class from the pyb module self.stretchCounter = 0 # Initializes the Stretch Counter to 0 on startup self.onesecond = 0x1388 # 5000 in Hexadecimal, equivalent to one second when used with the timer created in initTimer self.tenSeconds = 0xc350 # 50,000 in Hexadecimal, equivalent to ten seconds when used with the timer created in initTimer self.twentySeconds = 0x186a0 #100,000 in Hexadecimal, equivalent to twenty seconds when used with the timer created in initTimer self.sixtySeconds = 0x493e0 #300,000 in Hexadecimal, equivalent to sixty seconds when used with the timer created in initTimer self.tenminutes = 0x2dc6c0 #3,000,000 in Hexadecimal, equivalent to ten minutes when used with the timer created in initTimer self.hundredminutes = 0x1c9c380 #30,000,000 in Hexadecimal, equivalent to one hundred minutes when used with the timer created in initTimer self.myPrescaler = 0x20cf # 8399 in Hexadecimal, used with the timer in initTimer to run at a frequency of 5000 Hz. self.TimerNo = 0x2 # 2 in Hexadecimal, used to select the second timer for use self.months = [ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] # an array of the number of days in each month, each index is one month, starting from January self.last_saved_dateTime = [ 2015, 1, 1, 4, 0, 0, 0, 0 ] # Sets the first date saved, values are [year, month, day, weekday, hours, minutes, seconds, subseconds], where weekdays is 1-7 for Monday through Sunday, and subseconds counts down from 255 to 0 self.last_savedDay = 0 # Sets the last saved day as day zero self.curr_day = 0 # Sets the current saved day as zero
def now(): # Return the current time from the RTC in millisecs from year 2000 rtc = pyb.RTC() secs = utime.time() ms = 1000 * (255 - rtc.datetime()[7]) >> 8 if ms < 50: # Might have just rolled over secs = utime.time() return ms + 1000 * secs
def sync_rtc(self): tm = self.data.split(',')[1] dt = self.data.split(',')[9] rtc = pyb.RTC() try: rtc.calibration(cfg.RTC_CALIBRATION) log(self.__qualname__, 'rtc calibration factor', cfg.RTC_CALIBRATION) except Exception as err: log(self.__qualname__, 'sync_rtc', type(err).__name__, err, type='e') try: rtc.datetime(( int('20' + dt[4:6]), # yyyy int(dt[2:4]), # mm int(dt[0:2]), # dd 0, # 0 int(tm[0:2]), # hh int(tm[2:4]), # mm int(tm[4:6]), # ss float(tm[6:]))) # sss log(self.__qualname__, 'rtc synchronized') except Exception as err: log(self.__qualname__, 'sync_rtc', type(err).__name__, err, type='e')
def lpdelay(ms): global usb_connected rtc = pyb.RTC() if usb_connected: pyb.delay(ms) return rtc.wakeup(ms) pyb.stop() rtc.wakeup(None)
async def set_rtc(mqtt_link, local_time_offset): t = await mqtt_link.get_time() t += local_time_offset * 3600 rtc = pyb.RTC() tm = localtime(t) print('RTC set. Time:', tm) tm = tm[0:3] + (tm[6] + 1,) + tm[3:6] + (0,) rtc.datetime(tm) rtc_set = True
def lpdelay(ms): # Low power delay. Note stop() kills USB global usb_connected rtc = pyb.RTC() if usb_connected: pyb.delay(ms) return rtc.wakeup(ms) pyb.stop() rtc.wakeup(None)
def settime(self): self._log.debug("Hal: Entering SetTime") if self._utils.get_platform() == 'linux': import utime rtctime = utime.time() #Set start time core.upyeasy_starttime = rtctime return rtctime elif core._nic: rtctime = self.getntptime() else: return #no ntp hostname, no time if rtctime: self._log.debug("Hal: Received NTP Time: %d" % rtctime) else: self._log.debug("Hal: Received NTP Time: n.a.") return rtctime #store starttime core.upyeasy_starttime = rtctime self._log.debug("Hal: StartTime: %d" % core.upyeasy_starttime) if self._utils.get_platform() == 'pyboard': import pyb, utime #convert unix to soc epoch #rtctime-=946684800 tm = utime.localtime(rtctime) tm = tm[0:3] + (0, ) + tm[3:6] + (0, ) pyb.RTC().datetime(tm) elif self._utils.get_platform() == 'esp32': import machine, utime tm = utime.localtime(rtctime) tm = tm[0:3] + (0, ) + tm[3:6] + (0, ) # Set RTC time, if present if hasattr(machine, 'RTC'): machine.RTC().datetime(tm) else: self._log.debug("Hal: SetTime: NO RTC!") self._log.debug("Set time: " + "%04u-%02u-%02uT%02u:%02u:%02u" % utime.localtime()[0:6]) elif self._utils.get_platform() == 'esp8266': import machine, utime year, month, day, hour, minute, second, millis, _tzinfo = utime.localtime( rtctime) self._log.debug("Hal: Set time: %d-%02d-%02d %02d:%02d:%02d.%03d" % (year, month, day, hour, minute, second, millis)) rtc = machine.RTC() rtc.init((year, month, day, hour, minute, second, millis)) return rtctime
def now(): rtc = pyb.RTC() secs = utime.time() if d_series: ms = rtc.datetime()[7] // 1000 else: ms = 1000 * (255 - rtc.datetime()[7]) >> 8 if ms < 50: # Might have just rolled over secs = utime.time() return ms + 1000 * secs
def clock(tm): rtc = pyb.RTC() while True: t = rtc.datetime() tm.colon = t[6] & 1 tm.digit(0, t[4] // 10) tm.digit(1, t[4] % 10) tm.digit(2, t[5] // 10) tm.digit(3, t[5] % 10) tm.display()
def _run(self): rtc = pyb.RTC() rtc.wakeup(self._t_ms) t_ms = self._t_ms while True: if t_ms > 0: pyb.stop() yield if t_ms != self._t_ms: t_ms = self._t_ms if t_ms > 0: rtc.wakeup(t_ms) else: rtc.wakeup(None)
def _run(self): print('Low power mode is ON.') rtc = pyb.RTC() rtc.wakeup(self._t_ms) t_ms = self._t_ms while True: if t_ms > 0: pyb.stop() # Pending tasks run once, may change self._t_ms yield if t_ms != self._t_ms: # Has changed: update wakeup t_ms = self._t_ms if t_ms > 0: rtc.wakeup(t_ms) else: rtc.wakeup(None)
def _do_time(self, action): # TIME received from ESP8266 lnk = self._lnk try: t = int(action[0]) except ValueError: # Gibberish. lnk.quit('Invalid data from ESP8266') return self._time_valid = t > 0 if self._time_valid: rtc = pyb.RTC() tm = localtime(t) hours = (tm[3] + self._local_time_offset) % 24 tm = tm[0:3] + (tm[6] + 1,) + (hours,) + tm[4:6] + (0,) rtc.datetime(tm) self._rtc_last_syn = time() lnk.vbprint('time', localtime()) else: lnk.vbprint('Bad time received.')
def do_set_time(self, line): args = split_line(line) if (len(args) != 6): self.stderr.write('Expecting 6 arguments in the order: YYYY MM DD HH MM SS\n') return try: (year, month, day, hours, minutes, seconds) = [int(arg) for arg in args] except: self.stderr.write("Expecting numeric arguments\n") return # Run the date through mktime and back through localtime so that we # get a normalized date and time, and calculate the weekday t = time.mktime((year, month, day, hours, minutes, seconds, 0, 0, -1)) (year, month, day, hours, minutes, seconds, weekday, yearday) = time.localtime(t) rtc = pyb.RTC() # localtime weekday is 0-6, Monday is 0 # RTC weekday is 1-7, Monday is 1 rtc.datetime((year, month, day, weekday + 1, hours, minutes, seconds, 0)) self.stdout.write(ctime(time.time()))
def getTimeStr(): #t=time.localtime() #(year, month, mday, hour, minute, second, weekday, yearday) t = pyb.RTC().datetime( ) #(year, month, mday, tayofweack, hour, minute, second, ms) re = '' if (t[2] < 10): re = re + '0' re = re + str(t[2]) + '.' if (t[1] < 10): re = re + '0' re = re + str(t[1]) + '.' + str(t[0]) + '-' if (t[4] < 10): re = re + '0' re = re + str(t[4]) + ':' if (t[5] < 10): re = re + '0' re = re + str(t[5]) + ':' if (t[6] < 10): re = re + '0' re = re + str(t[6]) + '.' if (t[7] < 100): re = re + '0' if (t[7] < 10): re = re + '0' re = re + str(t[7]) return re #tt.mm.yyyy-hh:mm:ss.mmm
def __init__(self): print("ExiTrak.init") # self.led = pyb.LED(1) # self.sw = pyb.Switch() # self.PIN_ON = 1 self.rtc = pyb.RTC() self.stretchCounter = 0 self.onesecond = 0x1388 # 5000 Hz self.tenSeconds = 0xc350 # 50,000 self.twentySeconds = 0x186a0 #100,000 self.sixtySeconds = 0x493e0 #300,000 self.tenminutes = 0x2dc6c0 #3,000,000 self.hundredminutes = 0x1c9c380 #30,000,000 self.myPrescaler = 0x20cf # 8399 self.TimerNo = 0x2 #2 self.months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] self.last_saved_dateTime = [2015, 1, 1, 4, 0, 0, 0, 0] self.last_savedDay = 0 self.curr_day = 0
def aclock(): rtc = pyb.RTC() uv = lambda phi: cmath.rect(1, phi) # Return a unit vector of phase phi pi = cmath.pi days = ('Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun') months = ('Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec') # Instantiate Writer Writer.set_textpos(ssd, 0, 0) # In case previous tests have altered it wri = Writer(ssd, font_small, verbose=False) wri.set_clip(True, True, False) wri_tim = Writer(ssd, font_large, verbose=False) wri_tim.set_clip(True, True, False) # Instantiate displayable objects dial = Dial(wri, 2, 2, height=215, ticks=12, bdcolor=None, pip=True) lbltim = Label(wri_tim, 50, 230, '00.00.00') lbldat = Label(wri, 100, 230, 100) hrs = Pointer(dial) mins = Pointer(dial) hstart = 0 + 0.7j # Pointer lengths and position at top mstart = 0 + 0.92j while True: t = rtc.datetime( ) # (year, month, day, weekday, hours, minutes, seconds, subseconds) hang = -t[4] * pi / 6 - t[5] * pi / 360 # Angles of hands in radians mang = -t[5] * pi / 30 if abs(hang - mang) < pi / 360: # Avoid visually confusing overlap of hands hang += pi / 30 # by making hr hand lag slightly hrs.value(hstart * uv(hang)) mins.value(mstart * uv(mang)) lbltim.value('{:02d}.{:02d}'.format(t[4], t[5])) lbldat.value('{} {} {} {}'.format(days[t[3] - 1], t[2], months[t[1] - 1], t[0])) refresh(ssd) # Power saving: only refresh every 30s for _ in range(30): upower.lpdelay(1000) ssd.update() # Toggle VCOM
def set_time(y, m, d, h, min, s): """Set time on upy board.""" rtc = None try: import pyb rtc = pyb.RTC() rtc.datetime((y, m, d, None, h, min, s)) return rtc.datetime() except: try: import machine rtc = machine.RTC() if not rtc.synced(): try: rtc.datetime((y, m, d, None, h, min, s)) return rtc.datetime() except: rtc.init((y, m, d, h, min, s)) return rtc.now() except: return None
def __init__(self, *args, **kwargs): super(BlueSTProtocol, self).__init__(*args, **kwargs) self.rtc = pyb.RTC() self.rtc.init() self.rtc.calibration(-129) self.rtc.datetime((2017, 10, 6, 5, 16, 41, 0, 0)) self.bdaddr = bytes(reversed([0x12, 0x34, 0x00, 0xE1, 0x80, 0x02])) self.name = b'PyBLE' self.connection_handle = None self.service_handle = None self.dev_name_char_handle = None self.appearance_char_handle = None self.hw_serv_handle = None self.acc_gyro_mag_bluest_char_handle = None self.pressure_bluest_char_handle = None self.temperature_bluest_char_handle = None self.pwr_bluest_char_handle = None
def WriteDefaultPage(csocket, data): import pyb WriteHTMLHead(csocket, data, 'pyboardserver') csocket.send('<body>\n') csocket.send('<h1>Hello</h1>\n') csocket.send('<p>Server running on the pyboard.</p>\n') for x in data: csocket.send('<p>') csocket.send(x) csocket.send('</p>\n') t = pyb.millis() csocket.send('<p>') csocket.send(str(t)) csocket.send('</p>\n') dt = pyb.RTC().datetime() csocket.send('<p>') csocket.send(str(dt[2])) csocket.send('.') csocket.send(str(dt[1])) csocket.send('.') csocket.send(str(dt[0])) csocket.send(' ') csocket.send(str(dt[4])) csocket.send(':') csocket.send(str(dt[5])) csocket.send(':') csocket.send(str(dt[6])) csocket.send('.') csocket.send(str(dt[7])) csocket.send(' ') csocket.send('</p>\n') csocket.send('</body>\n') csocket.send('</html>\n')
def home_main(): global orientation, next_tick, tick ugfx.area(0, 0, 320, 240, sty_tb.background()) ugfx.set_default_font(ugfx.FONT_MEDIUM) win_bv = ugfx.Container(0, 0, 80, 25, style=sty_tb) win_wifi = ugfx.Container(82, 0, 60, 25, style=sty_tb) win_name = ugfx.Container(0, 25, 320, 240 - 25 - 60, style=dialogs.default_style_badge) win_text = ugfx.Container(0, 240 - 60, 320, 60, style=sty_tb) win_clock = ugfx.Container(250, 0, 70, 25, style=sty_tb) windows = [win_bv, win_wifi, win_clock, win_text] obj_name = apps.home.draw_name.draw(0, 25, win_name) buttons.init() gc.collect() ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD) hook_feeback = ugfx.List(0, 0, win_text.width(), win_text.height(), parent=win_text) win_bv.show() win_text.show() win_wifi.show() win_clock.show() # Create external hooks so other apps can run code in the context of # the home screen. # To do so an app needs to have an external.py with a tick() function. # The tick period will default to 60 sec, unless you define something # else via a "period" variable in the module context (use milliseconds) # If you set a variable "needs_wifi" in the module context tick() will # only be called if wifi is available # If you set a variable "needs_icon" in the module context tick() will # be called with a reference to a 25x25 pixel ugfx container that you # can modify external_hooks = [] icon_x = 150 for path in get_external_hook_paths(): try: module = __import__(path) if not hasattr(module, "tick"): raise Exception("%s must have a tick function" % path) hook = { "name": path[5:-9], "tick": module.tick, "needs_wifi": hasattr(module, "needs_wifi"), "period": module.period if hasattr(module, "period") else 60 * 1000, "next_tick_at": 0 } if hasattr(module, "needs_icon"): hook["icon"] = ugfx.Container(icon_x, 0, 25, 25) icon_x += 27 external_hooks.append(hook) except Exception as e: # Since we dont know what exception we're looking for, we cant do much print( "%s while parsing background task %s. This task will not run! " % (type(e).__name__, path[5:-9])) sys.print_exception(e) continue # If the module fails to load or dies during the setup, skip it backlight_adjust() inactivity = 0 last_rssi = 0 ## start connecting to wifi in the background wifi_timeout = 30 #seconds wifi_reconnect_timeout = 0 wifi_did_connect = 0 try: wifi.connect(wait=False, prompt_on_fail=False) except OSError: print("Connect failed") while True: pyb.wfi() ugfx.poll() if (next_tick <= pyb.millis()): tick = True next_tick = pyb.millis() + 1000 #if wifi still needs poking if (wifi_timeout > 0): if wifi.nic().is_connected(): wifi_timeout = -1 #wifi is connected, but if becomes disconnected, reconnect after 5 sec wifi_reconnect_timeout = 5 else: wifi.nic().update() if tick: tick = False ledg.on() if (wifi_timeout > 0): wifi_timeout -= 1 # change screen orientation ival = imu.get_acceleration() if ival['y'] < -0.5: if orientation != 0: ugfx.orientation(0) elif ival['y'] > 0.5: if orientation != 180: ugfx.orientation(180) if orientation != ugfx.orientation(): inactivity = 0 ugfx.area(0, 0, 320, 240, sty_tb.background()) orientation = ugfx.orientation() for w in windows: w.hide() w.show() apps.home.draw_name.draw(0, 25, win_name) #if wifi timeout has occured and wifi isnt connected in time if (wifi_timeout == 0) and not (wifi.nic().is_connected()): print("Giving up on Wifi connect") wifi_timeout = -1 wifi.nic().disconnect() #give up wifi_reconnect_timeout = 30 #try again in 30sec wifi_is_connected = wifi.nic().is_connected() #if not connected, see if we should try again if not wifi_is_connected: if wifi_did_connect > 0: wifi_did_connect = 0 if wifi_reconnect_timeout > 0: wifi_reconnect_timeout -= 1 if wifi_reconnect_timeout == 0: wifi_timeout = 60 #seconds wifi.connect(wait=False) else: # If we've just connected, set NTP time if wifi_did_connect == 0: wifi_did_connect = 1 ntp.set_NTP_time() ledg.on() # display the wifi logo rssi = wifi.nic().get_rssi() if rssi == 0: rssi = last_rssi else: last_rssi = rssi time = pyb.RTC().datetime() if time[0] >= 2016: draw_time(sty_tb.background(), pyb.RTC().datetime(), win_clock) draw_wifi(sty_tb.background(), rssi, wifi_is_connected, wifi_timeout > 0, win_wifi) battery_percent = onboard.get_battery_percentage() draw_battery(sty_tb.background(), battery_percent, win_bv) inactivity += 1 # turn off after some period # takes longer to turn off in the 'used' position if ugfx.orientation() == 180: inactivity_limit = 120 else: inactivity_limit = 30 if battery_percent > 120: #if charger plugged in if ugfx.backlight() == 0: ugfx.power_mode(ugfx.POWER_ON) ugfx.backlight(100) elif inactivity > inactivity_limit: low_power() else: backlight_adjust() ledg.off() for hook in external_hooks: try: if hook["needs_wifi"] and not wifi.nic().is_connected(): continue if hook["next_tick_at"] < pyb.millis(): text = None if "icon" in hook: text = hook["tick"](hook["icon"]) else: text = hook["tick"]() hook["next_tick_at"] = pyb.millis() + hook["period"] if text: if hook_feeback.count() > 10: hook_feeback.remove_item(0) hook_feeback.add_item(text) if hook_feeback.selected_index() >= ( hook_feeback.count() - 2): hook_feeback.selected_index(hook_feeback.count() - 1) except Exception as e: # if anything in the hook fails to work, we need to skip it print( "%s in %s background task. Not running again until next reboot! " % (type(e).__name__, hook['name'])) sys.print_exception(e) external_hooks.remove(hook) continue if buttons.is_pressed("BTN_MENU"): pyb.delay(20) break if buttons.is_pressed("BTN_A"): inactivity = 0 tick = True if buttons.is_pressed("BTN_B"): inactivity = 0 tick = True for hook in external_hooks: if "icon" in hook: hook["icon"].destroy() for w in windows: w.destroy() apps.home.draw_name.draw_destroy(obj_name) win_name.destroy() hook_feeback.destroy() if ugfx.backlight() == 0: ugfx.power_mode(ugfx.POWER_ON) ugfx.backlight(100) ugfx.orientation(180) #if we havnt connected yet then give up since the periodic function wont be poked if wifi_timeout >= 0: # not (wifi.nic().is_connected()): wifi.nic().disconnect()
import sensor, image, time, math, pyb rtc = pyb.RTC() #create variable to hold RTC object rtc.datetime( (2020, 1, 1, 1, 0, 0, 0, 0)) #set arbitrary datetime prior to initiation print("test start", rtc.datetime()) threshold_index_rd = 0 #0 for red threshold_index_gr = 1 #1 for green threshold_index_bl = 2 #2 for blue threshold_index_k = 3 #2 for Nothing r = 0 #incremental place holder - red g = 0 #incremental place holder - green b = 0 #incremental place holder - blue k = 0 #incremental place holder - NO COLOR r_s = 0 #initialize red state as 0 g_s = 0 #initialize green state as 0 b_s = 0 #initialize blue state as 0 k_s = 0 #initialize no state as 0 st = [] #list for holding color state gr_counter = 0 #counter for green color state after each array is filled rd_counter = 0 #counter for red color state after each array is filled bl_counter = 0 #counter for blue color state after each array is filled # Color Lab Tracking Thresholds (L Min, L Max, A Min, A Max, B Min, B Max) thresholds = [ (30, 100, 27, 127, -18, 69), # generic_red_thresholds (41, 92, -73, -35, -17, 54), # generic_green_thresholds
import pyb start_year = 2014 start_month = 8 start_day = 19 start_weekday = 2 # Tuesday (1-7 is Monday to Sunday) start_hours = 23 start_minutes = 22 start_seconds = 45 start_subseconds = 255 # this is a value that counts down from 255 to 0 clock = pyb.RTC() # datetime() takes one parameter (an 8-tuple) hence the double bracket (()) below clock.datetime((start_year, start_month, start_day, start_weekday, start_hours, start_minutes, start_seconds, start_subseconds)) # weekday in datetime() understands Monday as 1 and Sunday as 7 days_of_the_week = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] while True: # clock.datetime() returns an 8-tuple clock_tuple = clock.datetime() ''' year = clock_tuple()[0] month = clock_tuple()[1] day = clock_tuple()[2] weekday = clock_tuple()[3]
def test(): print(color.BOLD + "Iniciant test del sistema\n" + color.END) print("Comprovant sd...", end="") if 'sd' in os.listdir('/'): print(msg.OK) else: print(msg.ERR) print(color.RED + "Prem Ctrl+D, si no funciona..." + color.END) print(color.RED + "verifica l'estat de la SD" + color.END) print("Comprovant estat del MPU9250...", end="") if 12 in i2c_gy91.scan() or 118 in i2c_gy91.scan(): print(msg.OK) else: print(msg.ERR) print(color.RED + "Prem Ctrl+D, si no funciona..." + color.END) print( color.RED + "desconecta i reconecta la placa, sino revisa la tensió d'entrada a placa (5V) i les sortides (5V i 3v3)" + color.END) print("Comprovant estat del BMP280...", end="") if 104 in i2c_gy91.scan(): print(msg.OK) senBMP() print("Altitud actual: {alt}".format(alt=altitud)) else: print(msg.ERR) print(color.RED + "Prem Ctrl+D, si no funciona..." + color.END) print( color.RED + "desconecta i reconecta la placa, sino revisa la tensió d'entrada a placa (5V) i les sortides (5V i 3v3)" + color.END) print("Comprovant calibracio del sensor MPU9250...", end="") try: print("Offset magnetometre: {}".format(offsetMag)) print("Escala magnetometre: {}".format(scaleMag)) print("Offset giroscopi: {}".format(offsetGyro)) except: print(msg.nok) print(color.ORG + "No es disposa de dades de calibracio, executa calMPU()" + color.END) MPUCalibrat = False else: print(msg.OK) print( color.GREEN + "Dades de calibracio trobades, en cas de malfuncionament recalibrar amb calMPU()" + color.END) MPUCalibrat = True print("Comprovant conexió al sensor GPS...", end="") try: "" in uart_gps.readline() except: print(msg.ERR) print(color.RED + "Revisa la connexió del sensor" + color.END) else: print(msg.OK) for i in range(6): print("Comprovant cobertura GPS...", end="") try: #my_gps.local_offset = input("Introduir zona horaria: ") senGPS(500) except: print(msg.ERR) print(color.RED + "Ha succeit un error desconegut amb el modul senGPS" + color.END) break else: if my_gps.satellite_data_updated( ) and my_gps.satellites_in_use > 0: timezone = 2 dt = (int("20" + str(my_gps.date[2])), my_gps.date[1], my_gps.date[0], 1, my_gps.timestamp[0] + timezone, my_gps.timestamp[1], floor(my_gps.timestamp[2]), 0) pyb.RTC().datetime(dt) print(msg.OK) print(color.GREEN + "Hi ha senyal GPS" + color.END) print("S'han detectat {SATS} satel·lits".format( SATS=my_gps.satellites_in_use)) RealT = "{hora}:{minut}".format(hora=my_gps.timestamp[0], minut=my_gps.timestamp[1]) print( "Avui hauria de ser {DATE} i la hora actual hauria de ser {TIME}" .format(DATE=my_gps.date, TIME=RealT)) global logname logname = "20{y}_{m}_{d}_{h}_{mn}".format( y=my_gps.date[2], m=my_gps.date[1], d=my_gps.date[0], h=my_gps.timestamp[0] + timezone, mn=my_gps.timestamp[1]) print( "Les coordenades actuals del coet són: {lat} {lon}".format( lat=my_gps.latitude, lon=my_gps.longitude)) break elif i < 5: print(msg.NOK) print(color.ORG + "No hi ha cobertura GPS, reintentant..." + color.END) elif i == 5: print(msg.ERR) print( color.RED + "No s'ha pogut establir cobertura GPS, asegura que el coet es troba a l'exterior i executa test()" + color.END)
def log(t): """ A function for logging data from an MS5803 sensor to file at a regular interval. The function saves a line of text at each interval representing conductivity, temperature, pressure. The device then goes into standby mode for interval t. After interval t, the device awakes as if from a hard reset. The function is designed to be called from main.py. Puts device in standby mode upon completion. Parameters ---------- t: int logging interval (seconds) Example ------- To log data at 30 second intervals, save the following two lines as main.py >>> import logger_pres_temp as logger >>> logger.log(30) Note ---- For more robust logging, the lines related to the watchdog timer can be enabled by removing the comments. However, once the watchdog timer is set, it will automatically reset the board after the watchdog timer interval unless the timer is fed. This ensures that the board will continue to log even if an error is encountered, but it can cause unexpected results if the user wishes to interact with the board over serial. """ #from machine import WDT #wdt = machine.WDT(timeout=30000) red = pyb.LED(1) green = pyb.LED(2) yellow = pyb.LED(3) blue = pyb.LED(4) green.on() blue.on() #wait 10 seconds to allow user to jump in time.sleep(10) green.off() blue.off() #write file header outputtxt = 'date,time,pressure(mbar),temperature(C)\r\n' try: f = open('datalogCTD.txt','a') f.write(outputtxt) f.close() except: #briefly turn all leds on if fails to write red.on() green.on() yellow.on() blue.on() time.sleep(1) red.off() green.off() blue.off() yellow.off() start_time = time.time() while True: try: wdt.feed() except: pass #flash LED to let user know reading is being taken green.off() time.sleep(0.5) green.on() #define clock object, set next wakeup time (in milliseconds) and get the time rtc = pyb.RTC() datetime = rtc.datetime() log_time = start_time + t start_time = log_time try: wdt.feed() except: pass #define pressure sensor in Pressure.py. Connect SCL to X9, SDA to X10, VCC to Y7, GND to Y8 pres_power = Pin('Y7', Pin.OUT_PP) pres_gnd = Pin('Y8', Pin.OUT_PP) i2c = machine.I2C(scl='Y10', sda='Y9', freq = 100000) #write header in textfile #headerline = 'YY/MM/DD,Hour:Min:Sec,count1,count2,r1,r2,temp,pressure\r\n' #f = open('datalogDuw.txt','a') #f.write(headerline) #f.close() #read values from sensors try: [pres, ctemp] = pressure.MS5803(i2c, pres_power, pres_gnd) except: pres = -999 ctemp = -999 print('Pressure reading failed') yellow.on() time.sleep(1) yellow.off() try: wdt.feed() except: pass #write results to file outputtxt = ('%s/%s/%s,%s:%s:%s,' % (datetime[0], datetime[1], datetime[2], datetime[4], datetime[5], datetime[6])) outputtxt += ('%s,%s\r\n' % (pres, ctemp)) print (outputtxt) try: f = open('datalogCTD.txt','a') f.write(outputtxt) f.close() except: #briefly turn all leds on if fails to write red.on() green.on() yellow.on() blue.on() time.sleep(1) red.off() green.off() blue.off() yellow.off() sw = pyb.Switch() while time.time() < log_time: try: wdt.feed() except: pass green.on() time.sleep(0.005) green.off() if sw(): pyb.usb_mode(None) yellow.on() time.sleep(5) pyb.usb_mode('VCP+MSC') try: wdt.feed() except: pass break rtc.wakeup(2000) pyb.stop()
# Author: Peter Hinch # Copyright Peter Hinch 2018 Released under the MIT license. import utime import machine import sys DS3231_I2C_ADDR = 104 class DS3231Exception(OSError): pass if sys.platform == 'pyboard': import pyb rtc = pyb.RTC() else: try: rtc = machine.RTC() except: # Official ESP32 port print('warning: machine module does not support the RTC.') rtc = None def bcd2dec(bcd): return (((bcd & 0xf0) >> 4) * 10 + (bcd & 0x0f)) def dec2bcd(dec): tens, units = divmod(dec, 10) return (tens << 4) + units
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.sendto(NTP_QUERY, addr) msg = s.recv(48) s.close() import struct val = struct.unpack("!I", msg[40:44])[0] return val - NTP_DELTA def settime(): import time from pyb import RTC t = getntptime() tm = time.localtime(t) tm = tm[0:3] + (0,) + tm[3:6] + (0,) rtc = RTC() rtc.init() rtc.datetime(tm) nic = network.CC3100() nic.connect("<ssid>","<psk>") while (not nic.is_connected()): nic.update() pyb.delay(100) # set the RTC using time from ntp settime() # print out RTC datetime pyb.RTC().datetime()
def test_features(lcd): # 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(lcd160cr.PORTRAIT) 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))
import pyb a = pyb.RTC() a.datetime(2019, 10, 1, 10, 20, 30, 500) a.datetime() def testfunc(): print("wakeup test\n") a.wakeup(5, testfunc)