Lewis Solarin
Lewis Solarin

Reputation: 21

Cannot import machine module on MicroPython

When using an ESP8266 and sending files to the board via the WebRepl I can use the machine module when typing directly into the console. However, when I send a Python script that imports the machine module to the board and import it to the console and run the method the code that uses the module doesn't run. I can access other modules and run other code that I have sent onto the board. Also when writing the Python script importing the machine module appears as an error.

Can anyone tell me what I am doing wrong when importing the machine module from MicroPython?

from machine import Pin
from time import sleep
led = Pin(2, Pin.OUT)
for n in range(1,30):
    led.on()
    sleep(1)
    led.off()

Upvotes: 1

Views: 21109

Answers (3)

Kirill
Kirill

Reputation: 11

Make sure that you're trying to run your program on micropython board and not on your pc. If you're using Thonny Python IDE go to Run > Select interpreter. Then chose micropython (ESP8266) and proper port.

Upvotes: 1

Johny English
Johny English

Reputation: 176

it works like this (ESP8266, Nodemcu):

from machine import Pin
from utime import sleep
led = Pin(2, Pin.OUT) #GPIO2/D4
for n in range(1,30):
    led.value(0) #on
    sleep(1)
    led.value(1) #off
    sleep(1)


beware:

led.value(0) is turning led on, led.value(1) then off,
from utime import sleep becouse it's micropython not python,
you also had bad looping formula, sleep(1) was added by me at end

Upvotes: 1

MicrosMakeItBetter
MicrosMakeItBetter

Reputation: 24

After looking at your code, which most of the time will work on the MicroPython console on the esp8266. I have found in the programs I have written for the esp8266, I have had to import machine and then import time.

import machine
import time
LED4.Pin(4, machine.Pin.OUT, value=0)

That should run, and set the value of Pin 4 to 0 or low. You'll notice I didn't use the from machine import Pin.

In my experience, if you run it as

from machine import Pin

The program will not work correctly, I don't recall the error, just that it didn't run.

Secondly, the error will occur if the flash isn't working. You think it is flashed, but erroneous errors like this will happen. Use the esptool install to flash the esp8266 with the latest stable MicroPython and it should resolve the errors if the above does not work. I have had both instances work for me.

Upvotes: 0

Related Questions