Sending serial commands from python

RP2040 based microcontroller boards running MicroPython.
Target audience: MicroPython users with an RP2040 boards.
This does not include conventional Linux-based Raspberry Pi boards.
Post Reply
lxschwalb
Posts: 2
Joined: Thu Apr 21, 2022 9:35 am

Sending serial commands from python

Post by lxschwalb » Thu Apr 21, 2022 11:20 am

Hi, I'm new to micropython (and loving it so far), so maybe this is an easy to solve problem, but I've been stuck for a while.

Let's say the following code is uploaded to the main.py file on the microcontroller:

Code: Select all

from machine import Pin

led = Pin(25, Pin.OUT)
I want to then run python code on a laptop that sends, for example, led.value(1) to the microcontroller and have the microcontroller execute it, similar to the repl console. I don't want to use the repl console itself, as this should eventually be automated and integrated into a bigger system running in python on the laptop.

So far I have managed to send it, but not execute it. I run the following code on the laptop:

Code: Select all

import serial

ser = serial.Serial(port='/COM3', baudrate = 115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1)

ser.write(b'led.value(1)')
but the led does not turn on until I run ser.close() and then connect the repl console. This let's me think the microcontroller successfully received led.value(1), but does not run it until the repl console connects.

Is there something I can do to make the microcontroller run it without having to connect to the repl console? I've tried ser.write(b'\n') but it doesn't do anything.

I'm using the pico go extension in vs code on windows 10

Thanks in advance

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Sending serial commands from python

Post by Roberthh » Thu Apr 21, 2022 11:45 am

Unless you start a program on the board, it will have the REPL listening to the input. So you have daat like being sent from a concols. In you example, that means that commands have to be terminated with \r. Like:

ser.write('led.value(1)\r')

You can of course white a little program, that performs similar to REPL by reading a line and executing it. You can ass well us the raw mode. In that case a command sequence has to be terminated with \x04.

lxschwalb
Posts: 2
Joined: Thu Apr 21, 2022 9:35 am

Re: Sending serial commands from python

Post by lxschwalb » Thu Apr 21, 2022 2:39 pm

Thanks, the \r termination was exactly what I was looking for

Post Reply