Adding Serial communication to Python code

main
Gerardo Marx 1 day ago
parent 5f84e55424
commit e3ad755c5b

@ -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()
```
Loading…
Cancel
Save