JAB2401
JAB2401

Reputation: 11

Why can't VSCode load MicroPython 'machine'?

I have installed the MicroPython IDE and Python extension in accordance with the VSCode instructions. This is my first use of VSCode and I have searched for a solution and failed. when I try to debug this code:

import machine
import time
led = machine.Pin(2, machine.Pin.OUT)
button = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP)
while button.value():
    led.on()
    time.sleep(1)
    led.off()
    time.sleep(1)
led.on()

I get this result: Module Not Found Error "no module named 'machine' " I would very much appreciate your assistance.

Regards John

Upvotes: 1

Views: 4264

Answers (1)

Torben Klein
Torben Klein

Reputation: 3136

You are dealing with two separate Python environments:

  • The "PC Python" (also called CPython) on your development machine
  • MicroPython running on embedded device like ESP32.

When testing on PC, you are running your code in CPython. But if you transfer it to the device, it runs within MicroPython. Both environments are very similar but some differences exist.

The machine module is one such difference. It exists only in MicroPython and allows actual access to the hardware. Thus, if you run your program in CPython, you get exactly the error you described.

You can either test your program on an actual device. Or you "mock" the machine module, i.e. you create that module as "dummy" implementation for testing on PC. It would at least need to contain the Pin() class, which could for example print the state changes to command line.

There is an example for such a mock on GitHub: https://github.com/tflander/esp32-machine-emulator

A minimal example for your case: Create machine.py containing:

 class Pin:
   IN = 0
   OUT = 0
   PULL_UP = 0
   def __init__(self, number, mode=-1, pull=-1):
     self.number = number
   def on(self):
     print('Pin %d switches ON' % self.number)
   def off(self):
     print('Pin %d switches OFF' % self.number)
   def value(self):
     return 1
   # ... add other methods when needed ...

... and put it somewhere where your script can import it from.

Upvotes: 3

Related Questions