Search code examples
pythonvisual-studio-codeiotmicropython

ImportError when importing modules that exist in micropython


I am currently working on a project which involves taking soil moisture measurements using sensors and a Pycom LoPy4 mounted on the expansion board V3.1. I am currently using VS code as my IDE and using the pymakr extension to run the micropython with my board.

At the start of my project the import function was working correctly and I was using code directly copied from the internet as seen below and it would run without error:

import time
from machine import Pin
from onewire import DS18X20
from onewire import OneWire

# DS18B20 data line connected to pin P10
ow = OneWire(Pin('P10'))
temp = DS18X20(ow)

while True:
    print(temp.read_temp_async())
    time.sleep(1)
    temp.start_conversion()
    time.sleep(1)

This would import the onewire module and the sensor would take temp measurements.

Fast forward to now and for reasons I am unaware of, whenever I run the script I get a ImportError: no module named 'onewire'. I then tried to run a different library on a different project, this time trying to import the modules using the following code:

from lib import measureSensors
from lib import onewire;

Upon running this code I got basically the same error - ImportError: no module named 'lib.measureSensors'

I have also tried using the __init__.py method but that also does not seem to solve the problem I am having. I have attached a picture of my project tree below.

File tree

Weird thing is if I run these codes on pycharm or in VS code without using the pymakr extension, the code executes without any errors. The issue starts when running the code on pymakr and with the Lopy4 x expansion board V3.1.

Please, if anyone could help me in solving this issue, I would appreciate it greatly.

Thank you.


Solution

  • You can add the directory to the sys.path that python uses to find modules and import as usual:

    sys.path.insert(0, './lib')
    import measureSensors
    import onewire
    

    You can reference the module explicitly:

    import lib.measureSensors as measureSensors
    import lib.onewire as onewire