mu-editor / mu

A small, simple editor for beginner Python programmers. Written in Python and Qt5.
http://codewith.mu
GNU General Public License v3.0
1.4k stars 434 forks source link

Microbit: Import error #2277

Open mrunal093 opened 2 years ago

mrunal093 commented 2 years ago

What were you trying to do?

Calling a function from a user defined micropython file.

What steps did you take to trigger the issue?

I first move the robotbitV4.py file (which has the functions) using the file system. I then try to import it in the main file and call the functions in robotbitV4.py. Here is the main.py :

from microbit import *
import robobitV4 as r
display.show("2")
# port definitions.
M1A = 0x1
M1B = 0x2
M2A = 0x3
M2B = 0x4

# Motor drive test

r.setup()     # Set up the robobit
while True:
    display.show("S")   # show the loop started
    r.motor(M1A,100)    # max speed clockwise
    sleep(2000)         # pause to see change in motor speed
    display.show("R")   # display R for reverse
    r.motor(M1A,-100 )  # request max speed in reverse)
    sleep(2000)         # pause to see change in motor speed
    display.show("E")   # show at the end of loop
    sleep(1000)

_### And HERE is the robobitV4.py_

# ROBOTBIT version 3 to help alleviate memory issues in microbit version 1
from microbit import *
from time import sleep
from time import sleep_us
from machine import time_pulse_us
import math, ustruct

def setup():
# startup process - initialize i2c connection with motor driver
    i2c.init()
    i2c.write(0x40,bytearray([0x00, 0x00]))        #self.i2c.send(bytearray([0x00, 0x00]), self.address)
    set_all_pwm(0,0)
    i2c.write(0x40,bytearray([0x01, 0x04]))    # self.i2c.send(bytearray([0x01, 0x04]), self.address)
    i2c.write(0x40,bytearray([0x00, 0x01]))    #self.i2c.send(bytearray([0x00, 0x01]), self.address)
    sleep(0.005)  # wait for oscillator
    i2c.write(0x40, bytearray([0x00])) # write register we want to read from first
    mode1 = i2c.read(0x40,1)[0]
    mode1 = 0x00 & ~0x10
    i2c.write(0x40,bytearray([0x00, 0x00]))
    sleep(0.005)  # Wait for ascillator
    set_pwm_freq(50)
#    print("pwm data ",set_pwm(S1,None,None))

def set_all_pwm(on, off):
#  Sets all PWM channels."""
#    i2c.send(bytearray([0xFA, on & 0xFF]), self.address)
    i2c.write(0x40,bytearray([0xFA, on & 0xFF]))
#    i2c.send(bytearray([0xFB, on >> 8]), self.address)
    i2c.write(0x40,bytearray([0xFB, on >> 8]))  # Original Had error
#    i2c.send(bytearray([0xFC, off & 0xFF]), self.address)
    i2c.write(0x40,bytearray([0xFC, off & 0xFF]))
#    i2c.send(bytearray([0xFD, off >> 8]), self.address)
    i2c.write(0x40,bytearray([0xFD, off >> 8]))

def set_pwm_freq(freq_hz):
#Set the PWM frequency to the provided value in hertz."""
    prescaleval = 25000000.0    # 25MHz
    prescaleval /= 4096.0       # 12-bit
    prescaleval /= float(freq_hz)
    prescaleval -= 1.0
    # print('Setting PWM frequency to {0} Hz'.format(freq_hz))
    # print('Estimated pre-scale: {0}'.format(0xFEval))
    prescale = int(math.floor(prescaleval + 0.5))
    # print('Final pre-scale: {0}'.format(0xFE))
    # self.i2c.send(bytearray([0x00]), self.address) # write register we want to read from first
    #oldmode = self.i2c.mem_read(1, self.address, 0x00)[0]
    i2c.write(0x40, bytearray([0x00])) # These two lines replace mem_read
    oldmode = i2c.read(0x40,1)[0]
    newmode = (oldmode & 0x7F) | 0x10    # 0x10
    i2c.write(0x40,bytearray([0x00, newmode]))  # go to 0x10
    i2c.write(0x40,bytearray([0xFE, 0xFE]))
    i2c.write(0x40,bytearray([0x00, oldmode]))
    sleep(0.005)
    i2c.write(0x40,bytearray([0x00, oldmode | 0x80]))

def set_pwm(channel, on, off):
# Sets a single PWM channel."""
    if on is None or off is None:
    # self.i2c.send(bytearray([0x06+4*channel]), self.address) # write register we want to read from first
        #data = self.i2c.mem_read(4, self.address, 0x06+4*channel)
        i2c.write(0x40, bytearray([0x06+4*channel])) # These two lines replace mem_read
        data = i2c.read(0x40,4)
        return ustruct.unpack('<HH', data)

    i2c.write(0x40,bytearray([0x06+4*channel, on & 0xFF]))
    i2c.write(0x40,bytearray([0x07+4*channel, on >> 8]))
    i2c.write(0x40,bytearray([0x08+4*channel, off & 0xFF]))
    i2c.write(0x40,bytearray([0x09+4*channel, off >> 8]))

def servo(index, degree):
# Standard servo
# 50hz: 20,000 us
#    v_us = (degree*1000/180+1000)
#    value = int(v_us*4096/20000) * 2
    gain = int(430 - 90)/180
    value = int(degree*gain + 90)
    set_pwm(index+7, 0, value)

def servoc(index, pct_speed):
        # 50hz: 20,000 us
#        v_us = (degree*1000/180+1000)
#        value = int(v_us*4096/20000) * 2
# Positive speed is CW and Negative speed is CCW
    if pct_speed > 99:
        pct_speed = 99
    elif pct_speed < -99:
        pct_speed == -99
    value = 127 - int((pct_speed*127)/100)
    set_pwm(index+7, 0, value)

def servoc_stop(index):
    servoc(index,0)

def motor(index, speed):
    speed = speed * 16 # map from 256 to 4096
    if index>4 or index<=0:
        return
    pp = (index-1)*2
    pn = (index-1)*2+1
    if speed < 0:
        set_pwm(pp, 0, -speed)
        set_pwm(pn, 0, 0)
    else:
        set_pwm(pp, 0, 0)
        set_pwm(pn, 0, speed)

def distance(tp, ep):
    # tp is the trigger pin and ep is the echo pin
    ep.read_digital()  # clear echo
    tp.write_digital(1)  # Send a 10 microSec pulse
    sleep_us(10)  # wait 10 microSec
    tp.write_digital(0)  # Send pulse low
    ep.read_digital()  # clear echo signal - This is needed for a
    # pingSensor
    ts = time_pulse_us(ep, 1, 100000)  # Wait for echo or time out
    if ts > 0:
        return ts * 17 // 100  # if system did not time, then send
        # back a scaled value
    return ts  # Return error as a negative number (-1)

What did you expect to happen?

The motor function should have executed. (It works in the online micropython editor)

What actually happened?

It shows import error on line 7. I think it actually resets the entire microbit and deletes the robobitV4.py file which then leads to the import error.

Operating System Version

macOs monterey 12.4

Mu Version

Mu 1.1.1

Other Info

I tried the same approach and code in the online editor (https://python.microbit.org/v/2) and it works fine.

Editor Log

2022-06-27 17:48:36,922 - root:269(run) INFO: 

-----------------

Starting Mu 1.1.1
2022-06-27 17:48:36,923 - root:270(run) INFO: uname_result(system='Darwin', node='Mrunals-MacBook-Air.local', release='21.5.0', version='Darwin Kernel Version 21.5.0: Tue Apr 26 21:08:29 PDT 2022; root:xnu-8020.121.3~4/RELEASE_ARM64_T8101', machine='x86_64', processor='i386')
2022-06-27 17:48:36,943 - root:271(run) INFO: Platform: macOS-10.16-x86_64-i386-64bit
2022-06-27 17:48:36,943 - root:272(run) INFO: Python path: ['/', '/Applications/Mu Editor.app/Contents/Resources/Python/lib/python38.zip', '/Applications/Mu Editor.app/Contents/Resources/Python/lib/python3.8', '/Applications/Mu Editor.app/Contents/Resources/Python/lib/python3.8/lib-dynload', '/Applications/Mu Editor.app/Contents/Resources/Python/lib/python3.8/site-packages', '/Applications/Mu Editor.app/Contents/Resources/Python/lib/python3.8/site-packages/setuptools-57.4.0-py3.8.egg', '/Applications/Mu Editor.app/Contents/Resources/Python/lib/python3.8/site-packages/pip-21.1.3-py3.8.egg']
2022-06-27 17:48:36,943 - root:273(run) INFO: Language code: en_US
2022-06-27 17:48:36,943 - mu.settings:220(load) WARNING: No settings file found at /Users/mrunalshah/Library/Application Support/mu/settings.json; skipping
2022-06-27 17:48:36,944 - mu.settings:220(load) WARNING: No settings file found at /Users/mrunalshah/Library/Application Support/mu/session.json; skipping
2022-06-27 17:48:37,478 - mu.virtual_environment:585(ensure_and_create) INFO: Added log handler.
2022-06-27 17:48:37,479 - mu.virtual_environment:596(ensure_and_create) DEBUG: Checking virtual environment; attempt #1.
2022-06-27 17:48:37,479 - mu.virtual_environment:685(ensure_path) INFO: Virtual Environment found at: /Users/mrunalshah/Library/Application Support/mu/mu_venv-38-20220623-014200
2022-06-27 17:48:37,479 - mu.virtual_environment:698(ensure_interpreter) INFO: Interpreter found at: /Users/mrunalshah/Library/Application Support/mu/mu_venv-38-20220623-014200/bin/python
2022-06-27 17:48:37,479 - mu.virtual_environment:429(run_subprocess) INFO: Running ('/Users/mrunalshah/Library/Application Support/mu/mu_venv-38-20220623-014200/bin/python', '-c', 'import sys; print("%s%s" % sys.version_info[:2])') with kwargs {'shell': False}
2022-06-27 17:48:37,825 - mu.virtual_environment:441(run_subprocess) DEBUG: Process returned 0; output: 38
2022-06-27 17:48:37,826 - mu.virtual_environment:730(ensure_interpreter_version) INFO: Both interpreters at version 38
2022-06-27 17:48:37,826 - mu.virtual_environment:759(ensure_pip) INFO: Pip found at: /Users/mrunalshah/Library/Application Support/mu/mu_venv-38-20220623-014200/bin/pip
2022-06-27 17:48:37,826 - mu.virtual_environment:742(ensure_key_modules) DEBUG: Verifying import of: pgzero
2022-06-27 17:48:37,827 - mu.virtual_environment:429(run_subprocess) INFO: Running ('/Users/mrunalshah/Library/Application Support/mu/mu_venv-38-20220623-014200/bin/python', '-c', 'import pgzero') with kwargs {'shell': False}
2022-06-27 17:48:37,875 - mu.virtual_environment:441(run_subprocess) DEBUG: Process returned 0; output: 
2022-06-27 17:48:37,875 - mu.virtual_environment:742(ensure_key_modules) DEBUG: Verifying import of: flask
2022-06-27 17:48:37,875 - mu.virtual_environment:429(run_subprocess) INFO: Running ('/Users/mrunalshah/Library/Application Support/mu/mu_venv-38-20220623-014200/bin/python', '-c', 'import flask') with kwargs {'shell': False}
2022-06-27 17:48:38,077 - mu.virtual_environment:441(run_subprocess) DEBUG: Process returned 0; output: 
2022-06-27 17:48:38,087 - mu.virtual_environment:742(ensure_key_modules) DEBUG: Verifying import of: ipykernel
2022-06-27 17:48:38,087 - mu.virtual_environment:429(run_subprocess) INFO: Running ('/Users/mrunalshah/Library/Application Support/mu/mu_venv-38-20220623-014200/bin/python', '-c', 'import ipykernel') with kwargs {'shell': False}
2022-06-27 17:48:38,608 - mu.virtual_environment:441(run_subprocess) DEBUG: Process returned 0; output: 
2022-06-27 17:48:38,620 - mu.virtual_environment:742(ensure_key_modules) DEBUG: Verifying import of: ipython_genutils
2022-06-27 17:48:38,620 - mu.virtual_environment:429(run_subprocess) INFO: Running ('/Users/mrunalshah/Library/Application Support/mu/mu_venv-38-20220623-014200/bin/python', '-c', 'import ipython_genutils') with kwargs {'shell': False}
2022-06-27 17:48:38,653 - mu.virtual_environment:441(run_subprocess) DEBUG: Process returned 0; output: 
2022-06-27 17:48:38,653 - mu.virtual_environment:742(ensure_key_modules) DEBUG: Verifying import of: esptool
2022-06-27 17:48:38,653 - mu.virtual_environment:429(run_subprocess) INFO: Running ('/Users/mrunalshah/Library/Application Support/mu/mu_venv-38-20220623-014200/bin/python', '-c', 'import esptool') with kwargs {'shell': False}
2022-06-27 17:48:38,705 - mu.virtual_environment:441(run_subprocess) DEBUG: Process returned 0; output: 
2022-06-27 17:48:38,706 - mu.virtual_environment:628(ensure_and_create) INFO: Valid virtual environment found at /Users/mrunalshah/Library/Application Support/mu/mu_venv-38-20220623-014200
2022-06-27 17:48:38,706 - mu.settings:169(save) DEBUG: Saving to /Users/mrunalshah/Library/Application Support/mu/venv.json
2022-06-27 17:48:38,735 - mu.logic:768(__init__) INFO: Setting up editor.
2022-06-27 17:48:38,736 - mu.logic:789(__init__) INFO: Log directory: /Users/mrunalshah/Library/Logs/mu
2022-06-27 17:48:38,736 - mu.logic:790(__init__) INFO: Data directory: /Users/mrunalshah/Library/Application Support/mu
2022-06-27 17:48:38,736 - mu.logic:804(setup) INFO: Available modes: python, circuitpython, microbit, esp, web, pyboard, debugger, pygamezero, lego, pico
2022-06-27 17:48:38,737 - mu.modes.base:61(get_default_workspace) INFO: Using workspace /Users/mrunalshah/mu_code from settings file
2022-06-27 17:48:38,813 - mu.modes.base:61(get_default_workspace) INFO: Using workspace /Users/mrunalshah/mu_code from settings file
2022-06-27 17:48:38,813 - mu.logic:1549(change_mode) INFO: Workspace directory: /Users/mrunalshah/mu_code
2022-06-27 17:48:38,814 - mu.logic:878(restore_session) DEBUG: <SessionSettings from /Users/mrunalshah/Library/Application Support/mu/session.json>
2022-06-27 17:48:38,817 - mu.logic:1496(select_mode) INFO: Showing available modes: ['python', 'circuitpython', 'microbit', 'esp', 'web', 'pyboard', 'debugger', 'pygamezero', 'lego', 'pico']
2022-06-27 17:48:59,669 - mu.logic:1503(select_mode) INFO: New mode selected: microbit
2022-06-27 17:48:59,682 - mu.modes.base:61(get_default_workspace) INFO: Using workspace /Users/mrunalshah/mu_code from settings file
2022-06-27 17:48:59,682 - mu.logic:1549(change_mode) INFO: Workspace directory: /Users/mrunalshah/mu_code
2022-06-27 17:48:59,700 - mu.modes.base:61(get_default_workspace) INFO: Using workspace /Users/mrunalshah/mu_code from settings file
2022-06-27 17:48:59,700 - mu.logic:1549(change_mode) INFO: Workspace directory: /Users/mrunalshah/mu_code
2022-06-27 17:48:59,765 - mu.logic:962(restore_session) INFO: Starting with blank file.
2022-06-27 17:54:02,893 - mu.logic:747(check_usb) INFO: microbit device connected on port: /dev/cu.usbmodem1102(VID: 0x0D28, PID: 0x0204, manufacturer: 'ARM')
2022-06-27 17:54:11,227 - mu.modes.base:61(get_default_workspace) INFO: Using workspace /Users/mrunalshah/mu_code from settings file
2022-06-27 17:54:11,228 - mu.logic:1134(get_dialog_directory) INFO: Using path for file dialog: /Users/mrunalshah/mu_code
2022-06-27 17:54:23,214 - mu.interface.main:412(get_load_path) DEBUG: Getting load path: /Users/mrunalshah/mu_code/motor_M1A_Test.py
2022-06-27 17:54:23,215 - mu.logic:997(_load) INFO: Loading script from: /Users/mrunalshah/mu_code/motor_M1A_Test.py
2022-06-27 17:54:23,215 - mu.logic:326(read_and_decode) DEBUG: Trying to decode with utf-8
2022-06-27 17:54:23,215 - mu.logic:329(read_and_decode) INFO: Decoded with utf-8
2022-06-27 17:54:23,216 - mu.logic:342(read_and_decode) DEBUG: Detected newline '\n'
2022-06-27 17:54:23,216 - mu.logic:1096(_load) DEBUG: # Example of controlling one of the motor ports on the robotbit
# Description:  basic API calls to control the speed of a DC motor
# Author: S Brophy
# Date:  11/1/21

from microbit import *
from robobitV4 import *
display.show("2")
# port definitions.
M1A = 0x1
M1B = 0x2
M2A = 0x3
M2B = 0x4

# Motor drive test

setup()     # Set up the robobit
while True:
    display.show("S")   # show the loop started
    motor(M1A,100)    # max speed clockwise
    sleep(2000)         # pause to see change in motor speed
    display.show("R")   # display R for reverse
    motor(M1A,-100 )  # request max speed in reverse)
    sleep(2000)         # pause to see change in motor speed
  #  r.motorstop(M1A)    # Stop motor
    display.show("E")   # show at the end of loop
    sleep(1000)

2022-06-27 17:54:34,365 - mu.logic:1205(save_tab_to_file) INFO: Saving script to: /Users/mrunalshah/mu_code/motor_M1A_Test.py
2022-06-27 17:54:34,365 - mu.logic:1206(save_tab_to_file) DEBUG: # Example of controlling one of the motor ports on the robotbit
# Description:  basic API calls to control the speed of a DC motor
# Author: S Brophy
# Date:  11/1/21

from microbit import *
imprt robobitV4 import *
display.show("2")
# port definitions.
M1A = 0x1
M1B = 0x2
M2A = 0x3
M2B = 0x4

# Motor drive test

setup()     # Set up the robobit
while True:
    display.show("S")   # show the loop started
    motor(M1A,100)    # max speed clockwise
    sleep(2000)         # pause to see change in motor speed
    display.show("R")   # display R for reverse
    motor(M1A,-100 )  # request max speed in reverse)
    sleep(2000)         # pause to see change in motor speed
  #  r.motorstop(M1A)    # Stop motor
    display.show("E")   # show at the end of loop
    sleep(1000)

2022-06-27 17:54:34,371 - mu.logic:1588(autosave) INFO: Autosave detected and saved changes in /Users/mrunalshah/mu_code/motor_M1A_Test.py.
2022-06-27 17:54:39,364 - mu.logic:1205(save_tab_to_file) INFO: Saving script to: /Users/mrunalshah/mu_code/motor_M1A_Test.py
2022-06-27 17:54:39,365 - mu.logic:1206(save_tab_to_file) DEBUG: # Example of controlling one of the motor ports on the robotbit
# Description:  basic API calls to control the speed of a DC motor
# Author: S Brophy
# Date:  11/1/21

from microbit import *
imprt robobitV4 as 
display.show("2")
# port definitions.
M1A = 0x1
M1B = 0x2
M2A = 0x3
M2B = 0x4

# Motor drive test

setup()     # Set up the robobit
while True:
    display.show("S")   # show the loop started
    motor(M1A,100)    # max speed clockwise
    sleep(2000)         # pause to see change in motor speed
    display.show("R")   # display R for reverse
    motor(M1A,-100 )  # request max speed in reverse)
    sleep(2000)         # pause to see change in motor speed
  #  r.motorstop(M1A)    # Stop motor
    display.show("E")   # show at the end of loop
    sleep(1000)

2022-06-27 17:54:39,370 - mu.logic:1588(autosave) INFO: Autosave detected and saved changes in /Users/mrunalshah/mu_code/motor_M1A_Test.py.
2022-06-27 17:54:44,362 - mu.logic:1205(save_tab_to_file) INFO: Saving script to: /Users/mrunalshah/mu_code/motor_M1A_Test.py
2022-06-27 17:54:44,363 - mu.logic:1206(save_tab_to_file) DEBUG: # Example of controlling one of the motor ports on the robotbit
# Description:  basic API calls to control the speed of a DC motor
# Author: S Brophy
# Date:  11/1/21

from microbit import *
imprt robobitV4 as r
display.show("2")
# port definitions.
M1A = 0x1
M1B = 0x2
M2A = 0x3
M2B = 0x4

# Motor drive test

r.setup()     # Set up the robobit
while True:
    display.show("S")   # show the loop started
    motor(M1A,100)    # max speed clockwise
    sleep(2000)         # pause to see change in motor speed
    display.show("R")   # display R for reverse
    motor(M1A,-100 )  # request max speed in reverse)
    sleep(2000)         # pause to see change in motor speed
  #  r.motorstop(M1A)    # Stop motor
    display.show("E")   # show at the end of loop
    sleep(1000)

2022-06-27 17:54:44,368 - mu.logic:1588(autosave) INFO: Autosave detected and saved changes in /Users/mrunalshah/mu_code/motor_M1A_Test.py.
2022-06-27 17:54:49,364 - mu.logic:1205(save_tab_to_file) INFO: Saving script to: /Users/mrunalshah/mu_code/motor_M1A_Test.py
2022-06-27 17:54:49,364 - mu.logic:1206(save_tab_to_file) DEBUG: # Example of controlling one of the motor ports on the robotbit
# Description:  basic API calls to control the speed of a DC motor
# Author: S Brophy
# Date:  11/1/21

from microbit import *
imprt robobitV4 as r
display.show("2")
# port definitions.
M1A = 0x1
M1B = 0x2
M2A = 0x3
M2B = 0x4

# Motor drive test

r.setup()     # Set up the robobit
while True:
    display.show("S")   # show the loop started
    r.motor(M1A,100)    # max speed clockwise
    sleep(2000)         # pause to see change in motor speed
    display.show("R")   # display R for reverse
    motor(M1A,-100 )  # request max speed in reverse)
    sleep(2000)         # pause to see change in motor speed
  #  r.motorstop(M1A)    # Stop motor
    display.show("E")   # show at the end of loop
    sleep(1000)

2022-06-27 17:54:49,369 - mu.logic:1588(autosave) INFO: Autosave detected and saved changes in /Users/mrunalshah/mu_code/motor_M1A_Test.py.
2022-06-27 17:54:54,363 - mu.logic:1205(save_tab_to_file) INFO: Saving script to: /Users/mrunalshah/mu_code/motor_M1A_Test.py
2022-06-27 17:54:54,364 - mu.logic:1206(save_tab_to_file) DEBUG: # Example of controlling one of the motor ports on the robotbit
# Description:  basic API calls to control the speed of a DC motor
# Author: S Brophy
# Date:  11/1/21

from microbit import *
imprt robobitV4 as r
display.show("2")
# port definitions.
M1A = 0x1
M1B = 0x2
M2A = 0x3
M2B = 0x4

# Motor drive test

r.setup()     # Set up the robobit
while True:
    display.show("S")   # show the loop started
    r.motor(M1A,100)    # max speed clockwise
    sleep(2000)         # pause to see change in motor speed
    display.show("R")   # display R for reverse
    r.motor(M1A,-100 )  # request max speed in reverse)
    sleep(2000)         # pause to see change in motor speed
  #  r.motorstop(M1A)    # Stop motor
    display.show("E")   # show at the end of loop
    sleep(1000)

2022-06-27 17:54:54,369 - mu.logic:1588(autosave) INFO: Autosave detected and saved changes in /Users/mrunalshah/mu_code/motor_M1A_Test.py.
2022-06-27 17:55:04,364 - mu.logic:1205(save_tab_to_file) INFO: Saving script to: /Users/mrunalshah/mu_code/motor_M1A_Test.py
2022-06-27 17:55:04,365 - mu.logic:1206(save_tab_to_file) DEBUG: # Example of controlling one of the motor ports on the robotbit
# Description:  basic API calls to control the speed of a DC motor
# Author: S Brophy
# Date:  11/1/21

from microbit import *
imprt robobitV4 as r
display.show("2")
# port definitions.
M1A = 0x1
M1B = 0x2
M2A = 0x3
M2B = 0x4

# Motor drive test

r.setup()     # Set up the robobit
while True:
    display.show("S")   # show the loop started
    r.motor(M1A,100)    # max speed clockwise
    sleep(2000)         # pause to see change in motor speed
    display.show("R")   # display R for reverse
    r.motor(M1A,-100 )  # request max speed in reverse)
    sleep(2000)         # pause to see change in motor speed

    display.show("E")   # show at the end of loop
    sleep(1000)

2022-06-27 17:55:04,370 - mu.logic:1588(autosave) INFO: Autosave detected and saved changes in /Users/mrunalshah/mu_code/motor_M1A_Test.py.
2022-06-27 17:55:09,364 - mu.logic:1205(save_tab_to_file) INFO: Saving script to: /Users/mrunalshah/mu_code/motor_M1A_Test.py
2022-06-27 17:55:09,366 - mu.logic:1206(save_tab_to_file) DEBUG: # Example of controlling one of the motor ports on the robotbit
# Description:  basic API calls to control the speed of a DC motor
# Author: S Brophy
# Date:  11/1/21

from microbit import *
imprt robobitV4 as r
display.show("2")
# port definitions.
M1A = 0x1
M1B = 0x2
M2A = 0x3
M2B = 0x4

# Motor drive test

r.setup()     # Set up the robobit
while True:
    display.show("S")   # show the loop started
    r.motor(M1A,100)    # max speed clockwise
    sleep(2000)         # pause to see change in motor speed
    display.show("R")   # display R for reverse
    r.motor(M1A,-100 )  # request max speed in reverse)
    sleep(2000)         # pause to see change in motor speed
    display.show("E")   # show at the end of loop
    sleep(1000)

2022-06-27 17:55:09,371 - mu.logic:1588(autosave) INFO: Autosave detected and saved changes in /Users/mrunalshah/mu_code/motor_M1A_Test.py.
2022-06-27 17:55:10,092 - mu.modes.base:61(get_default_workspace) INFO: Using workspace /Users/mrunalshah/mu_code from settings file
2022-06-27 17:55:10,114 - mu.modes.microbit:570(toggle_files) INFO: Toggle filesystem on.
2022-06-27 17:55:13,546 - mu.interface.panes:530(dropEvent) INFO: Copying '/Users/mrunalshah/mu_code/robobitV4.py' to device.
2022-06-27 17:55:21,090 - mu.modes.microbit:574(toggle_files) INFO: Toggle filesystem off.
2022-06-27 17:55:21,757 - mu.modes.microbit:273(flash) INFO: Preparing to flash script.
2022-06-27 17:55:21,757 - mu.modes.microbit:280(flash) DEBUG: Python script from 'motor_M1A_Test.py' tab:
2022-06-27 17:55:21,758 - mu.modes.microbit:281(flash) DEBUG: b'# Example of controlling one of the motor ports on the robotbit\n# Description:  basic API calls to control the speed of a DC motor\n# Author: S Brophy\n# Date:  11/1/21\n\nfrom microbit import *\nimprt robobitV4 as r\ndisplay.show("2")\n# port definitions.\nM1A = 0x1\nM1B = 0x2\nM2A = 0x3\nM2B = 0x4\n\n# Motor drive test\n\nr.setup()     # Set up the robobit\nwhile True:\n    display.show("S")   # show the loop started\n    r.motor(M1A,100)    # max speed clockwise\n    sleep(2000)         # pause to see change in motor speed\n    display.show("R")   # display R for reverse\n    r.motor(M1A,-100 )  # request max speed in reverse)\n    sleep(2000)         # pause to see change in motor speed\n    display.show("E")   # show at the end of loop\n    sleep(1000)\n'
2022-06-27 17:55:21,797 - mu.modes.microbit:229(find_microbit) INFO: Path to micro:bit: /Volumes/MICROBIT
2022-06-27 17:55:21,797 - mu.modes.microbit:235(find_microbit) INFO: Serial port: /dev/cu.usbmodem1102
2022-06-27 17:55:21,797 - mu.modes.microbit:236(find_microbit) INFO: Device serial number: 9904360259004e45005e300800000049000000009796990b
2022-06-27 17:55:21,797 - mu.modes.microbit:237(find_microbit) INFO: Board ID: 0x9904
2022-06-27 17:55:21,798 - mu.modes.microbit:358(flash) INFO: Checking target device.
2022-06-27 17:55:22,340 - mu.modes.microbit:246(get_device_micropython_version) INFO: {'sysname': 'microbit', 'nodename': 'microbit', 'release': '2.0.0', 'version': 'micro:bit v2.0.0+b51a405 on 2021-06-30; MicroPython v1.15-64-g1e2f0d280 on 2021-06-30', 'machine': 'micro:bit with nRF52833'}
2022-06-27 17:55:22,342 - mu.modes.microbit:254(get_device_micropython_version) INFO: Board MicroPython: 2.0.0
2022-06-27 17:55:22,342 - mu.modes.microbit:367(flash) INFO: Mu MicroPython: 2.0.0
2022-06-27 17:55:22,344 - mu.modes.microbit:474(copy_main) INFO: Copying main.py onto device
2022-06-27 17:55:22,344 - mu.modes.microbit:481(copy_main) INFO: ["fd = open('main.py', 'wb')", 'f = fd.write', "f(b'# Example of controlling one of the motor ports on the robotbit\\n')", "f(b'# Description:  basic API calls to control the speed of a DC mot')", "f(b'or\\n# Author: S Brophy\\n# Date:  11/1/21\\n\\nfrom microbit import *\\ni')", 'f(b\'mprt robobitV4 as r\\ndisplay.show("2")\\n# port definitions.\\nM1A = \')', "f(b'0x1\\nM1B = 0x2\\nM2A = 0x3\\nM2B = 0x4\\n\\n# Motor drive test\\n\\nr.setup()')", 'f(b\'     # Set up the robobit\\nwhile True:\\n    display.show("S")   # \')', "f(b'show the loop started\\n    r.motor(M1A,100)    # max speed clockw')", "f(b'ise\\n    sleep(2000)         # pause to see change in motor speed')", 'f(b\'\\n    display.show("R")   # display R for reverse\\n    r.motor(M1A\')', "f(b',-100 )  # request max speed in reverse)\\n    sleep(2000)        ')", 'f(b\' # pause to see change in motor speed\\n    display.show("E")   # \')', "f(b'show at the end of loop\\n    sleep(1000)\\n')", 'fd.close()']
2022-06-27 17:55:23,386 - mu.modes.microbit:408(flash) WARNING: Could not copy file to device.
2022-06-27 17:55:23,386 - mu.modes.microbit:409(flash) ERROR: Could not enter raw REPL.
2022-06-27 17:55:23,387 - mu.modes.microbit:410(flash) INFO: Falling back to old-style flashing.
2022-06-27 17:55:23,387 - mu.modes.microbit:444(flash_attached) INFO: Flashing new MicroPython runtime onto device
2022-06-27 17:55:38,849 - mu.modes.microbit:459(flash_finished) INFO: Flashing successful.
2022-06-27 17:55:49,399 - mu.logic:1205(save_tab_to_file) INFO: Saving script to: /Users/mrunalshah/mu_code/motor_M1A_Test.py
2022-06-27 17:55:49,399 - mu.logic:1206(save_tab_to_file) DEBUG: # Example of controlling one of the motor ports on the robotbit
# Description:  basic API calls to control the speed of a DC motor
# Author: S Brophy
# Date:  11/1/21

from microbit import *
import robobitV4 as r
display.show("2")
# port definitions.
M1A = 0x1
M1B = 0x2
M2A = 0x3
M2B = 0x4

# Motor drive test

r.setup()     # Set up the robobit
while True:
    display.show("S")   # show the loop started
    r.motor(M1A,100)    # max speed clockwise
    sleep(2000)         # pause to see change in motor speed
    display.show("R")   # display R for reverse
    r.motor(M1A,-100 )  # request max speed in reverse)
    sleep(2000)         # pause to see change in motor speed
    display.show("E")   # show at the end of loop
    sleep(1000)

2022-06-27 17:55:49,401 - mu.logic:1588(autosave) INFO: Autosave detected and saved changes in /Users/mrunalshah/mu_code/motor_M1A_Test.py.
2022-06-27 17:55:51,044 - mu.modes.microbit:273(flash) INFO: Preparing to flash script.
2022-06-27 17:55:51,044 - mu.modes.microbit:280(flash) DEBUG: Python script from 'motor_M1A_Test.py' tab:
2022-06-27 17:55:51,044 - mu.modes.microbit:281(flash) DEBUG: b'# Example of controlling one of the motor ports on the robotbit\n# Description:  basic API calls to control the speed of a DC motor\n# Author: S Brophy\n# Date:  11/1/21\n\nfrom microbit import *\nimport robobitV4 as r\ndisplay.show("2")\n# port definitions.\nM1A = 0x1\nM1B = 0x2\nM2A = 0x3\nM2B = 0x4\n\n# Motor drive test\n\nr.setup()     # Set up the robobit\nwhile True:\n    display.show("S")   # show the loop started\n    r.motor(M1A,100)    # max speed clockwise\n    sleep(2000)         # pause to see change in motor speed\n    display.show("R")   # display R for reverse\n    r.motor(M1A,-100 )  # request max speed in reverse)\n    sleep(2000)         # pause to see change in motor speed\n    display.show("E")   # show at the end of loop\n    sleep(1000)\n'
2022-06-27 17:55:51,077 - mu.modes.microbit:229(find_microbit) INFO: Path to micro:bit: /Volumes/MICROBIT
2022-06-27 17:55:51,078 - mu.modes.microbit:235(find_microbit) INFO: Serial port: /dev/cu.usbmodem1102
2022-06-27 17:55:51,078 - mu.modes.microbit:236(find_microbit) INFO: Device serial number: 9904360259004e45005e300800000049000000009796990b
2022-06-27 17:55:51,078 - mu.modes.microbit:237(find_microbit) INFO: Board ID: 0x9904
2022-06-27 17:55:51,078 - mu.modes.microbit:358(flash) INFO: Checking target device.
2022-06-27 17:55:51,620 - mu.modes.microbit:246(get_device_micropython_version) INFO: {'sysname': 'microbit', 'nodename': 'microbit', 'release': '2.0.0', 'version': 'micro:bit v2.0.0+b51a405 on 2021-06-30; MicroPython v1.15-64-g1e2f0d280 on 2021-06-30', 'machine': 'micro:bit with nRF52833'}
2022-06-27 17:55:51,621 - mu.modes.microbit:254(get_device_micropython_version) INFO: Board MicroPython: 2.0.0
2022-06-27 17:55:51,621 - mu.modes.microbit:367(flash) INFO: Mu MicroPython: 2.0.0
2022-06-27 17:55:51,622 - mu.modes.microbit:474(copy_main) INFO: Copying main.py onto device
2022-06-27 17:55:51,623 - mu.modes.microbit:481(copy_main) INFO: ["fd = open('main.py', 'wb')", 'f = fd.write', "f(b'# Example of controlling one of the motor ports on the robotbit\\n')", "f(b'# Description:  basic API calls to control the speed of a DC mot')", "f(b'or\\n# Author: S Brophy\\n# Date:  11/1/21\\n\\nfrom microbit import *\\ni')", 'f(b\'mport robobitV4 as r\\ndisplay.show("2")\\n# port definitions.\\nM1A =\')', "f(b' 0x1\\nM1B = 0x2\\nM2A = 0x3\\nM2B = 0x4\\n\\n# Motor drive test\\n\\nr.setup(')", 'f(b\')     # Set up the robobit\\nwhile True:\\n    display.show("S")   #\')', "f(b' show the loop started\\n    r.motor(M1A,100)    # max speed clock')", "f(b'wise\\n    sleep(2000)         # pause to see change in motor spee')", 'f(b\'d\\n    display.show("R")   # display R for reverse\\n    r.motor(M1\')', "f(b'A,-100 )  # request max speed in reverse)\\n    sleep(2000)       ')", 'f(b\'  # pause to see change in motor speed\\n    display.show("E")   #\')', "f(b' show at the end of loop\\n    sleep(1000)\\n')", 'fd.close()']
2022-06-27 17:55:52,669 - mu.modes.microbit:408(flash) WARNING: Could not copy file to device.
2022-06-27 17:55:52,669 - mu.modes.microbit:409(flash) ERROR: Could not enter raw REPL.
2022-06-27 17:55:52,670 - mu.modes.microbit:410(flash) INFO: Falling back to old-style flashing.
2022-06-27 17:55:52,670 - mu.modes.microbit:444(flash_attached) INFO: Flashing new MicroPython runtime onto device
2022-06-27 17:56:08,079 - mu.modes.microbit:459(flash_finished) INFO: Flashing successful.
2022-06-27 17:56:16,023 - mu.modes.base:112(open) INFO: Connecting to REPL on port: /dev/cu.usbmodem1102
2022-06-27 17:56:16,037 - mu.modes.base:130(open) INFO: Connected to REPL on port: /dev/cu.usbmodem1102
2022-06-27 17:56:16,054 - mu.modes.base:503(add_repl) INFO: Started REPL on port: /dev/cu.usbmodem1102
2022-06-27 17:56:16,055 - mu.modes.base:474(toggle_repl) INFO: Toggle REPL on.
2022-06-27 18:05:59,287 - mu.logic:1134(get_dialog_directory) INFO: Using path for file dialog: /Users/mrunalshah/mu_code
2022-06-27 18:06:01,208 - mu.interface.main:412(get_load_path) DEBUG: Getting load path: /Users/mrunalshah/mu_code/robobitV4.py
2022-06-27 18:06:01,208 - mu.logic:997(_load) INFO: Loading script from: /Users/mrunalshah/mu_code/robobitV4.py
2022-06-27 18:06:01,209 - mu.logic:326(read_and_decode) DEBUG: Trying to decode with utf-8
2022-06-27 18:06:01,209 - mu.logic:329(read_and_decode) INFO: Decoded with utf-8
2022-06-27 18:06:01,209 - mu.logic:342(read_and_decode) DEBUG: Detected newline '\n'
2022-06-27 18:06:01,209 - mu.logic:1096(_load) DEBUG: # ROBOTBIT version 3 to help alleviate memory issues in microbit version 1
from microbit import *
from time import sleep
from time import sleep_us
from machine import time_pulse_us
import math, ustruct

def setup():
# startup process - initialize i2c connection with motor driver
    i2c.init()
    i2c.write(0x40,bytearray([0x00, 0x00]))        #self.i2c.send(bytearray([0x00, 0x00]), self.address)
    set_all_pwm(0,0)
    i2c.write(0x40,bytearray([0x01, 0x04]))    # self.i2c.send(bytearray([0x01, 0x04]), self.address)
    i2c.write(0x40,bytearray([0x00, 0x01]))    #self.i2c.send(bytearray([0x00, 0x01]), self.address)
    sleep(0.005)  # wait for oscillator
    i2c.write(0x40, bytearray([0x00])) # write register we want to read from first
    mode1 = i2c.read(0x40,1)[0]
    mode1 = 0x00 & ~0x10
    i2c.write(0x40,bytearray([0x00, 0x00]))
    sleep(0.005)  # Wait for ascillator
    set_pwm_freq(50)
#    print("pwm data ",set_pwm(S1,None,None))

def set_all_pwm(on, off):
#  Sets all PWM channels."""
#    i2c.send(bytearray([0xFA, on & 0xFF]), self.address)
    i2c.write(0x40,bytearray([0xFA, on & 0xFF]))
#    i2c.send(bytearray([0xFB, on >> 8]), self.address)
    i2c.write(0x40,bytearray([0xFB, on >> 8]))  # Original Had error
#    i2c.send(bytearray([0xFC, off & 0xFF]), self.address)
    i2c.write(0x40,bytearray([0xFC, off & 0xFF]))
#    i2c.send(bytearray([0xFD, off >> 8]), self.address)
    i2c.write(0x40,bytearray([0xFD, off >> 8]))

def set_pwm_freq(freq_hz):
#Set the PWM frequency to the provided value in hertz."""
    prescaleval = 25000000.0    # 25MHz
    prescaleval /= 4096.0       # 12-bit
    prescaleval /= float(freq_hz)
    prescaleval -= 1.0
    # print('Setting PWM frequency to {0} Hz'.format(freq_hz))
    # print('Estimated pre-scale: {0}'.format(0xFEval))
    prescale = int(math.floor(prescaleval + 0.5))
    # print('Final pre-scale: {0}'.format(0xFE))
    # self.i2c.send(bytearray([0x00]), self.address) # write register we want to read from first
    #oldmode = self.i2c.mem_read(1, self.address, 0x00)[0]
    i2c.write(0x40, bytearray([0x00])) # These two lines replace mem_read
    oldmode = i2c.read(0x40,1)[0]
    newmode = (oldmode & 0x7F) | 0x10    # 0x10
    i2c.write(0x40,bytearray([0x00, newmode]))  # go to 0x10
    i2c.write(0x40,bytearray([0xFE, 0xFE]))
    i2c.write(0x40,bytearray([0x00, oldmode]))
    sleep(0.005)
    i2c.write(0x40,bytearray([0x00, oldmode | 0x80]))

def set_pwm(channel, on, off):
# Sets a single PWM channel."""
    if on is None or off is None:
    # self.i2c.send(bytearray([0x06+4*channel]), self.address) # write register we want to read from first
        #data = self.i2c.mem_read(4, self.address, 0x06+4*channel)
        i2c.write(0x40, bytearray([0x06+4*channel])) # These two lines replace mem_read
        data = i2c.read(0x40,4)
        return ustruct.unpack('<HH', data)

    i2c.write(0x40,bytearray([0x06+4*channel, on & 0xFF]))
    i2c.write(0x40,bytearray([0x07+4*channel, on >> 8]))
    i2c.write(0x40,bytearray([0x08+4*channel, off & 0xFF]))
    i2c.write(0x40,bytearray([0x09+4*channel, off >> 8]))

def servo(index, degree):
# Standard servo
# 50hz: 20,000 us
#    v_us = (degree*1000/180+1000)
#    value = int(v_us*4096/20000) * 2
    gain = int(430 - 90)/180
    value = int(degree*gain + 90)
    set_pwm(index+7, 0, value)

def servoc(index, pct_speed):
        # 50hz: 20,000 us
#        v_us = (degree*1000/180+1000)
#        value = int(v_us*4096/20000) * 2
# Positive speed is CW and Negative speed is CCW
    if pct_speed > 99:
        pct_speed = 99
    elif pct_speed < -99:
        pct_speed == -99
    value = 127 - int((pct_speed*127)/100)
    set_pwm(index+7, 0, value)

def servoc_stop(index):
    servoc(index,0)

def motor(index, speed):
    speed = speed * 16 # map from 256 to 4096
    if index>4 or index<=0:
        return
    pp = (index-1)*2
    pn = (index-1)*2+1
    if speed < 0:
        set_pwm(pp, 0, -speed)
        set_pwm(pn, 0, 0)
    else:
        set_pwm(pp, 0, 0)
        set_pwm(pn, 0, speed)

def distance(tp, ep):
    # tp is the trigger pin and ep is the echo pin
    ep.read_digital()  # clear echo
    tp.write_digital(1)  # Send a 10 microSec pulse
    sleep_us(10)  # wait 10 microSec
    tp.write_digital(0)  # Send pulse low
    ep.read_digital()  # clear echo signal - This is needed for a
    # pingSensor
    ts = time_pulse_us(ep, 1, 100000)  # Wait for echo or time out
    if ts > 0:
        return ts * 17 // 100  # if system did not time, then send
        # back a scaled value
    return ts  # Return error as a negative number (-1)

2022-06-27 18:08:42,715 - mu.logic:1416(show_admin) INFO: Showing admin with logs from /Users/mrunalshah/Library/Logs/mu/mu.log
2022-06-27 18:08:42,717 - mu.virtual_environment:922(installed_packages) INFO: Discovering installed third party modules in venv.
2022-06-27 18:08:42,718 - mu.virtual_environment:114(run_blocking) INFO: About to run blocking /Users/mrunalshah/Library/Application Support/mu/mu_venv-38-20220623-014200/bin/pip with args ['list', '--disable-pip-version-check'] and envvars {}
2022-06-27 18:08:43,229 - mu.virtual_environment:164(wait) DEBUG: Finished: True; exitStatus 0; exitCode 0
2022-06-27 18:08:43,230 - mu.virtual_environment:249(run) DEBUG: Process output: Package           Version
----------------- -------
appnope           0.1.2
asttokens         2.0.5
backcall          0.2.0
bitstring         3.1.9
black             22.1.0
cffi              1.15.0
click             8.0.4
cryptography      36.0.1
decorator         5.1.1
ecdsa             0.17.0
entrypoints       0.4
esptool           3.2
executing         0.8.2
Flask             2.0.3
ipykernel         5.5.6
ipython           8.0.1
ipython-genutils  0.2.0
itsdangerous      2.1.0
jedi              0.18.1
Jinja2            3.0.3
jupyter-client    7.1.2
jupyter-core      4.9.2
MarkupSafe        2.1.0
matplotlib-inline 0.1.3
mypy-extensions   0.4.3
nest-asyncio      1.5.4
numpy             1.22.2
parso             0.8.3
pathspec          0.9.0
pexpect           4.8.0
pgzero            1.2.1
pickleshare       0.7.5
pip               22.0.3
platformdirs      2.5.1
prompt-toolkit    3.0.28
ptyprocess        0.7.0
pure-eval         0.2.2
pycparser         2.21
pygame            2.1.2
Pygments          2.11.2
pyserial          3.5
python-dateutil   2.8.2
pyzmq             22.3.0
reedsolo          1.5.4
setuptools        60.9.3
six               1.16.0
stack-data        0.2.0
tomli             2.0.1
tornado           6.1
traitlets         5.1.1
typing_extensions 4.1.1
wcwidth           0.2.5
Werkzeug          2.0.3
wheel             0.37.1
2022-06-27 18:08:43,230 - mu.virtual_environment:931(installed_packages) INFO: []
carlosperate commented 2 years ago

Hi @mrunal093, thanks for the report!

If I understood correctly this is your current setup and flashing method:

Is this correct?

If this is the case, it's because when a custom MicroPython is added to the settings Mu doesn't have a way to know if the MicroPython running on your micro:bit is the same as the hex file specified. For this reason it has to flash MicroPython every time the "Flash" button is pressed, and then it sends main.py. Flashing MicroPython means erasing all the micro:bit flash contents, so the library you've previously transfered is erased.

In this case what you need to do is first click "Flash" and then transfer any library via the "Files" panel.

carlosperate commented 2 years ago

Hi @mrunal093, did the instructions from my last message help?