Serielle Kommunikation zwischen Pi pico und 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
mistermful
Posts: 1
Joined: Tue Apr 26, 2022 8:44 am

Serielle Kommunikation zwischen Pi pico und Python

Post by mistermful » Tue Apr 26, 2022 8:59 am

Guten Tag zusammen,

Ich versuche von Python (was auf meinem PC läuft) an die Serielle Schnittstelle des Pico einen String oder Integer zu senden. Leider funktioniert das ganze nicht so wie geplant. Ich kann zwar Strings die vom Pico geschickt werden lesen, jedoch nicht welche schreiben. Wenn ich die Schnittstelle über puTTY öffne funktioniert lesen und schreiben wunderbar. Ich glaube an der Form wie ich den String schicke passt etwas nicht. Ich habe schon probiert den String mit der Funktion .decode() umzuwandeln oder auch mittels bytes(string, "utf-8) leider beides nicht funktioniert.

Hier der Code wo in Thonny läuft:
f

Code: Select all

rom machine import Pin
led = Pin(25, Pin.OUT)
while True:
    data = input()
    print(data)   
    if data == "1":
        led.on()
    if data == "0":
        led.off()
Und hier de Ptyhon Code:

Code: Select all

import serial
import time
pico = serial.Serial('COM3', 115200) # serial port | Baud rate
def write(x):
    pico.write(bytes( x, 'UTF-8'))
    time.sleep(0.05)
def read():
    data = pico.readline()
    data = data.replace(b'\n', b'').replace(b'\r', b'') # format string
    time.sleep(0.05)
    return data
pico.write(1)
print(pico.read())
Vielleicht kann mir jemand hier weiterhelfen!

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

Re: Serielle Kommunikation zwischen Pi pico und Python

Post by Roberthh » Tue Apr 26, 2022 9:31 am

input() expects a string, terminated with \r. And in your Pi Pico code, you test against a string, but in the PC code, you try to send a single byte. And it is not wise to use the names write and read for your own functions. You get confused with pico.write() and pico.read().
So: In your PC code, change the function def write() for instance to

def write_serial(x):
pico.write(x + "\r")

and similar
def read()

into

def read_serial()

and then call:

write_serial("1")
and
read_serial()

Do NOT use pico.write() and pico.read() in the main program, because then your own functions will not be called.

Post Reply