Friday, March 22, 2024

How to do 2-way bidirectional communication between Raspberry Pi and Pico over USB serial

Original Source: https://forums.raspberrypi.com/viewtopic.php?t=300474

 

Spent some time looking for this really basic trivial thing that I thought would be easy to find online. 

So I want my Pico to constantly send sensor readings to my Pi, and then my Pi to react in real-time to changes in the sensor readings. So I wanted to be able to have a Python program running in the background on my Pi that constantly receives data from my Pico and reacts to it in real time.

Anyway, here is my fully tested and fully working code (yes I tested it, yes it works):

Code that runs on the Pico:

import select
from machine import Pin, Timer
import sys
import time

led = Pin(25, Pin.OUT)

count = 0
while True:
    count += 1
    time.sleep(0.5)
    led.toggle()
    if select.select([sys.stdin],[],[],0)[0]:
        line = sys.stdin.readline()        
        print("You said:", line, count)
    else:
        print("..", count)

The LED toggle is there to tell you that the program is running - if the LED is blinking, then it means the program is running.

Code that runs on the Raspberry Pi:

#!/usr/bin/env python3
import time
import os
import serial

if os.path.exists('/dev/ttyACM0') == True:
    # Set timeout=0 for nonblocking read
    # Set timeout=None for blocking read
    ser = serial.Serial('/dev/ttyACM0', 115200, timeout=None)
    time.sleep(1)
else:
    print("ttyACM0 not detected")
    exit()

last_time = time.time()
while True:
    # VERY IMPORTANT: Input MUST be newline-terminated!!!!!
    if time.time() - last_time > 1:
        last_time = time.time()
        ser.write(bytes("hello\n".encode('ascii')))
    print("Waiting for readline to return...")
    pico_data = ser.readline()
    pico_data = pico_data.decode("utf-8","ignore")
    print(pico_data)

Original Source: https://forums.raspberrypi.com/viewtopic.php?t=300474


No comments:

Post a Comment