From e3ad755c5b92ec9842ba59eb3e25a006c8689fb1 Mon Sep 17 00:00:00 2001 From: Gerardo Marx Date: Mon, 6 Oct 2025 16:57:50 +0000 Subject: [PATCH] Adding Serial communication to Python code --- Readme.md | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/Readme.md b/Readme.md index b25231a..019c9ea 100644 --- a/Readme.md +++ b/Readme.md @@ -218,3 +218,60 @@ void loop() { } } ``` + +# Python serial communication + +First install Srialpy with: +```sh +pip3 install serialpy +``` + +```python +import serial +import time + +ser = serial.Serial('/dev/cu.usbmodem101', 115200, timeout=1) # Adjust port +time.sleep(2) # Wait for Arduino reset + +# Example: read temperatures +ser.write(b'T1\n') +t1 = ser.readline().decode().strip() +time.sleep(1) # Wait for Arduino reset +print('T1 =', t1, '°C') +ser.close() +``` + +For multiple readings and data store: +```python +import numpy as np +import matplotlib.pyplot as plt +m = 300 #seconds +Q = np.zeros(m) +T = np.zeros(m) +Q[10:250] = 100 +plt.plot(Q,'.k') +plt.show() +``` + +```python +import time + +ser = serial.Serial('/dev/cu.usbmodem101', 115200, timeout=1) # Adjust port +time.sleep(2) # Wait for Arduino reset + +for i in range(m)): + value = Q[i] + command = f"Q1 {value}\n" + ser.write(command.encode('ascii')) + ser.write(b'T1\n') + t1 = ser.readline().decode().strip() + T[i] = t1 + time.sleep(1) + if (i%10==0): + print(Q[i], T[i]) + +value = 0 +command = f"Q1 {value}\n" +ser.write(command.encode('ascii')) +ser.close() +``` \ No newline at end of file