utime.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. :mod:`utime` -- time related functions
  2. ======================================
  3. .. module:: utime
  4. :synopsis: time related functions
  5. |see_cpython_module| :mod:`python:time`.
  6. The ``utime`` module provides functions for getting the current time and date,
  7. measuring time intervals, and for delays.
  8. **Time Epoch**: Unix port uses standard for POSIX systems epoch of
  9. 1970-01-01 00:00:00 UTC. However, embedded ports use epoch of
  10. 2000-01-01 00:00:00 UTC.
  11. **Maintaining actual calendar date/time**: This requires a
  12. Real Time Clock (RTC). On systems with underlying OS (including some
  13. RTOS), an RTC may be implicit. Setting and maintaining actual calendar
  14. time is responsibility of OS/RTOS and is done outside of MicroPython,
  15. it just uses OS API to query date/time. On baremetal ports however
  16. system time depends on ``machine.RTC()`` object. The current calendar time
  17. may be set using ``machine.RTC().datetime(tuple)`` function, and maintained
  18. by following means:
  19. * By a backup battery (which may be an additional, optional component for
  20. a particular board).
  21. * Using networked time protocol (requires setup by a port/user).
  22. * Set manually by a user on each power-up (many boards then maintain
  23. RTC time across hard resets, though some may require setting it again
  24. in such case).
  25. If actual calendar time is not maintained with a system/MicroPython RTC,
  26. functions below which require reference to current absolute time may
  27. behave not as expected.
  28. Functions
  29. ---------
  30. .. function:: localtime([secs])
  31. Convert a time expressed in seconds since the Epoch (see above) into an 8-tuple which
  32. contains: (year, month, mday, hour, minute, second, weekday, yearday)
  33. If secs is not provided or None, then the current time from the RTC is used.
  34. * year includes the century (for example 2014).
  35. * month is 1-12
  36. * mday is 1-31
  37. * hour is 0-23
  38. * minute is 0-59
  39. * second is 0-59
  40. * weekday is 0-6 for Mon-Sun
  41. * yearday is 1-366
  42. .. function:: mktime()
  43. This is inverse function of localtime. It's argument is a full 8-tuple
  44. which expresses a time as per localtime. It returns an integer which is
  45. the number of seconds since Jan 1, 2000.
  46. .. function:: sleep(seconds)
  47. Sleep for the given number of seconds. Some boards may accept *seconds* as a
  48. floating-point number to sleep for a fractional number of seconds. Note that
  49. other boards may not accept a floating-point argument, for compatibility with
  50. them use `sleep_ms()` and `sleep_us()` functions.
  51. .. function:: sleep_ms(ms)
  52. Delay for given number of milliseconds, should be positive or 0.
  53. .. function:: sleep_us(us)
  54. Delay for given number of microseconds, should be positive or 0.
  55. .. function:: ticks_ms()
  56. Returns an increasing millisecond counter with an arbitrary reference point, that
  57. wraps around after some value.
  58. The wrap-around value is not explicitly exposed, but we will
  59. refer to it as *TICKS_MAX* to simplify discussion. Period of the values is
  60. *TICKS_PERIOD = TICKS_MAX + 1*. *TICKS_PERIOD* is guaranteed to be a power of
  61. two, but otherwise may differ from port to port. The same period value is used
  62. for all of `ticks_ms()`, `ticks_us()`, `ticks_cpu()` functions (for
  63. simplicity). Thus, these functions will return a value in range [*0* ..
  64. *TICKS_MAX*], inclusive, total *TICKS_PERIOD* values. Note that only
  65. non-negative values are used. For the most part, you should treat values returned
  66. by these functions as opaque. The only operations available for them are
  67. `ticks_diff()` and `ticks_add()` functions described below.
  68. Note: Performing standard mathematical operations (+, -) or relational
  69. operators (<, <=, >, >=) directly on these value will lead to invalid
  70. result. Performing mathematical operations and then passing their results
  71. as arguments to `ticks_diff()` or `ticks_add()` will also lead to
  72. invalid results from the latter functions.
  73. .. function:: ticks_us()
  74. Just like `ticks_ms()` above, but in microseconds.
  75. .. function:: ticks_cpu()
  76. Similar to `ticks_ms()` and `ticks_us()`, but with the highest possible resolution
  77. in the system. This is usually CPU clocks, and that's why the function is named that
  78. way. But it doesn't have to be a CPU clock, some other timing source available in a
  79. system (e.g. high-resolution timer) can be used instead. The exact timing unit
  80. (resolution) of this function is not specified on ``utime`` module level, but
  81. documentation for a specific port may provide more specific information. This
  82. function is intended for very fine benchmarking or very tight real-time loops.
  83. Avoid using it in portable code.
  84. Availability: Not every port implements this function.
  85. .. function:: ticks_add(ticks, delta)
  86. Offset ticks value by a given number, which can be either positive or negative.
  87. Given a *ticks* value, this function allows to calculate ticks value *delta*
  88. ticks before or after it, following modular-arithmetic definition of tick values
  89. (see `ticks_ms()` above). *ticks* parameter must be a direct result of call
  90. to `ticks_ms()`, `ticks_us()`, or `ticks_cpu()` functions (or from previous
  91. call to `ticks_add()`). However, *delta* can be an arbitrary integer number
  92. or numeric expression. `ticks_add()` is useful for calculating deadlines for
  93. events/tasks. (Note: you must use `ticks_diff()` function to work with
  94. deadlines.)
  95. Examples::
  96. # Find out what ticks value there was 100ms ago
  97. print(ticks_add(time.ticks_ms(), -100))
  98. # Calculate deadline for operation and test for it
  99. deadline = ticks_add(time.ticks_ms(), 200)
  100. while ticks_diff(deadline, time.ticks_ms()) > 0:
  101. do_a_little_of_something()
  102. # Find out TICKS_MAX used by this port
  103. print(ticks_add(0, -1))
  104. .. function:: ticks_diff(ticks1, ticks2)
  105. Measure ticks difference between values returned from `ticks_ms()`, `ticks_us()`,
  106. or `ticks_cpu()` functions, as a signed value which may wrap around.
  107. The argument order is the same as for subtraction
  108. operator, ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``.
  109. However, values returned by `ticks_ms()`, etc. functions may wrap around, so
  110. directly using subtraction on them will produce incorrect result. That is why
  111. `ticks_diff()` is needed, it implements modular (or more specifically, ring)
  112. arithmetics to produce correct result even for wrap-around values (as long as they not
  113. too distant inbetween, see below). The function returns **signed** value in the range
  114. [*-TICKS_PERIOD/2* .. *TICKS_PERIOD/2-1*] (that's a typical range definition for
  115. two's-complement signed binary integers). If the result is negative, it means that
  116. *ticks1* occurred earlier in time than *ticks2*. Otherwise, it means that
  117. *ticks1* occurred after *ticks2*. This holds **only** if *ticks1* and *ticks2*
  118. are apart from each other for no more than *TICKS_PERIOD/2-1* ticks. If that does
  119. not hold, incorrect result will be returned. Specifically, if two tick values are
  120. apart for *TICKS_PERIOD/2-1* ticks, that value will be returned by the function.
  121. However, if *TICKS_PERIOD/2* of real-time ticks has passed between them, the
  122. function will return *-TICKS_PERIOD/2* instead, i.e. result value will wrap around
  123. to the negative range of possible values.
  124. Informal rationale of the constraints above: Suppose you are locked in a room with no
  125. means to monitor passing of time except a standard 12-notch clock. Then if you look at
  126. dial-plate now, and don't look again for another 13 hours (e.g., if you fall for a
  127. long sleep), then once you finally look again, it may seem to you that only 1 hour
  128. has passed. To avoid this mistake, just look at the clock regularly. Your application
  129. should do the same. "Too long sleep" metaphor also maps directly to application
  130. behavior: don't let your application run any single task for too long. Run tasks
  131. in steps, and do time-keeping inbetween.
  132. `ticks_diff()` is designed to accommodate various usage patterns, among them:
  133. * Polling with timeout. In this case, the order of events is known, and you will deal
  134. only with positive results of `ticks_diff()`::
  135. # Wait for GPIO pin to be asserted, but at most 500us
  136. start = time.ticks_us()
  137. while pin.value() == 0:
  138. if time.ticks_diff(time.ticks_us(), start) > 500:
  139. raise TimeoutError
  140. * Scheduling events. In this case, `ticks_diff()` result may be negative
  141. if an event is overdue::
  142. # This code snippet is not optimized
  143. now = time.ticks_ms()
  144. scheduled_time = task.scheduled_time()
  145. if ticks_diff(scheduled_time, now) > 0:
  146. print("Too early, let's nap")
  147. sleep_ms(ticks_diff(scheduled_time, now))
  148. task.run()
  149. elif ticks_diff(scheduled_time, now) == 0:
  150. print("Right at time!")
  151. task.run()
  152. elif ticks_diff(scheduled_time, now) < 0:
  153. print("Oops, running late, tell task to run faster!")
  154. task.run(run_faster=true)
  155. Note: Do not pass `time()` values to `ticks_diff()`, you should use
  156. normal mathematical operations on them. But note that `time()` may (and will)
  157. also overflow. This is known as https://en.wikipedia.org/wiki/Year_2038_problem .
  158. .. function:: time()
  159. Returns the number of seconds, as an integer, since the Epoch, assuming that
  160. underlying RTC is set and maintained as described above. If an RTC is not set, this
  161. function returns number of seconds since a port-specific reference point in time (for
  162. embedded boards without a battery-backed RTC, usually since power up or reset). If you
  163. want to develop portable MicroPython application, you should not rely on this function
  164. to provide higher than second precision. If you need higher precision, use
  165. `ticks_ms()` and `ticks_us()` functions, if you need calendar time,
  166. `localtime()` without an argument is a better choice.
  167. .. admonition:: Difference to CPython
  168. :class: attention
  169. In CPython, this function returns number of
  170. seconds since Unix epoch, 1970-01-01 00:00 UTC, as a floating-point,
  171. usually having microsecond precision. With MicroPython, only Unix port
  172. uses the same Epoch, and if floating-point precision allows,
  173. returns sub-second precision. Embedded hardware usually doesn't have
  174. floating-point precision to represent both long time ranges and subsecond
  175. precision, so they use integer value with second precision. Some embedded
  176. hardware also lacks battery-powered RTC, so returns number of seconds
  177. since last power-up or from other relative, hardware-specific point
  178. (e.g. reset).