*Update, new main.py for pico and read_serial for RPI 4. *I am having the same problem with uart.write(), see below.
I am trying to communicate with a raspberry pi pico with my raspberry pi 4 over uart (via USB). The below code does transmit data, but I am only receiving data from the print statement. The goal of this project is to create a realtime datalogger on raspberry pi taking advantage of the ADCs and temperature sensor on the pico (main.py).
import os
import utime
from machine import ADC
from machine import UART
from machine import Pin
temp_sensor = ADC(4) # Default connection of temperature sensor
led = Pin(25, Pin.OUT)
def temperature():
# get raw sensor data
raw_sensor_data = temp_sensor.read_u16()
# convert raw value to equivalent voltage
sensor_voltage = (raw_sensor_data / 65535)*3.3
# convert voltage to temperature (celcius)
temperature = 27. - (sensor_voltage - 0.706)/0.001721
return temperature
#print setup information :
print("OS Name : ",os.uname())
#uart = machine.UART(0, baudrate = 9600)
uart = UART(0, baudrate = 9600)
print("UART Info : ", uart)
utime.sleep(3)
while True:
temp = temperature()
#t2 = temperature()
#print(str(temp))
print(str(temp))
#uart.write(str(temp) + '\n')
uart.write(str.encode(str(temp) +'\n')) #Does nothing but needed.
pin.toggle()
utime.sleep(1)
And the code on my raspberry pi 4 is:
import time
import serial
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
plt.ion() ## Note this correction
fig=plt.figure()
#plt.axis([0,1000,0,1])
ser = serial.Serial(
#port='/dev/ttySO', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
port = '/dev/ttyACM0',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.SEVENBITS
)
x=list()
y=list()
i=0
counter=0
while True:
if ser.inWaiting() > 0:
temp = ser.readline()
x.append(i);
y.append(temp);
#temperature = str(x).encode("utf-8")
print(temp)
plt.plot(x,y, color='black');
i+=1;
#fig.gca().relim()
fig.gca().autoscale_view()
plt.show()
plt.pause(0.0001)
The output in the terminal on my RPI 4 is:
27.2332
26.443
26.443
26.564
There is an extra new line between. If I remove print(str(temp)) from the pico code I get nothing. I can put just about anything in uart.write(str.encode(str(temp) +'\n')) and still receive the print statement, but without the uart.write() I will receive nothing. I replaced the uart.write() with uart.write(str.encode(str(temp) + 'chicken' + '\n')) and I still get the print statement followed by extra blank line.
Note: I have made some good progress creating my realtime data plotting. Making whole new plots in the while loop every iteration is wasteful and causes problems if I let it plot for long time. I will be implementing https://stackoverflow.com/questions/11874767/how-do-i-plot-in-real-time-in-a-while-loop-using-matplotlib soon.