pythonmicropythonbbc-microbit

How load libraries to micro:bit v2?


I recently decided to write a library for the ds18b20 sensor for microbits, but I ran into a problem, I need other libraries for example datetime.

I tried to just install the library and run the code.

from microbit import *
from datetime import datetime


class DS18B20:
    def __init__(self, pin):
        self.pin = pin

    def sleep_us(self, us):
        lasttime = running_time() / 1000
        nowtime = running_time() / 1000
        while (nowtime - lasttime) < us:
            nowtime = running_time() / 1000

    def DS18B20Reset(self):
        self.pin.write_digital(0)
        self.sleep_us(750)
        self.pin.write_digital(1)
        self.sleep_us(15)

    def DS18B20WriteByte(self, data):
        _data = 0
        for i in range(8):
            _data = data & 0x01
            data >>= 1
            if _data:
                self.pin.write_digital(0)
                self.sleep_us(2)
                self.pin.write_digital(1)
                self.sleep_us(60)
            else:
                self.pin.write_digital(0)
                self.sleep_us(60)
                self.pin.write_digital(1)
                self.sleep_us(2)```

But, i got an error:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
ImportError: no module named 'datetime'

Solution

  • There is no native datetime module available in Micropython. However, it looks like an implementation is available in the micropython-lib repository.

    You can install the datetime.py file on your Micro:Bit the same way you installed your own code and see if it meets your needs. The implementation is not going to be as full featured as the standard Python datetime module.


    Looking at the code you've posted, other than your import statement you don't appear to actually be using the datetime module, so perhaps the easiest solution is just to remove the import statement.