Kyrylo Kalashnikov
Kyrylo Kalashnikov

Reputation: 71

Inconsistent behavior of pyserial and rshell when executed in a .py file

I am trying to program my lego mindstorms inventor robot using python and this pypi package. It basically uses rshell to communicate with the lego robot that is running micropython. Here is the code that I am trying to execute.

from mindstorms import Hub
hub = Hub()
motor = hub.port.E.motor
print(motor)
motor.run_for_degrees(270)

When I run this code line by line in the python shell in the terminal everything works as expected. The motor turns. However, if I put this in a .py file, I get this error. rshell.pyboard.PyboardError: ('exception', b'', b'Traceback (most recent call last):\r\n File "<stdin>", line 1, in <module>\r\nAttributeError: \'NoneType\' object has no attribute \'run_for_degrees\'\r\n' Seems like the issue is that the motor is not being detected by the brain when I run the script in a .py file. I made another script for diagnostics. It is sending messages directly to the robot without using the pypi package.

board = Pyboard(device)
board.enter_raw_repl()
print(board.exec_("import hub;print(hub.port.A.info())"))

The result is "None". The brain by itself is detected because commands such as print(board.exec_("import hub;print(hub.info())")) run successfully. When I am trying to get any information about the port, the result is None, which makes me believe that the connected motor is not detected by the .py file. Again, if I simply run all this code in the python shell it works perfectly. I am confused by this irregular behavior.

Here are the steps that I took to troubleshot this(none of them worked):

Any suggestions why this would this problem occur?

Upvotes: 0

Views: 125

Answers (1)

Kyrylo Kalashnikov
Kyrylo Kalashnikov

Reputation: 71

The issue is that you need to wait a few seconds after the initialization of the Mindstorms brain before performing any kind of motor initialization.

from mindstorms import Hub;
import time
hub = Hub();
time.sleep(2)
print(hub.port.A.motor);
hub.port.A.motor.run_for_degrees(30);

Upvotes: 1

Related Questions