i want to read msg...but when i running python program, i can not open arduino serial monitor. actually, i have some data send to python to calculate and want to send back the answer to arduino for do something.
while True:
ser = serial.Serial('/dev/ttyUSB0',4800)
r1=ser.readline()
# x = [400, 150, 150, 130, 140] sample data from arduino it's will keep change
x = r1.decode('utf8').rstrip().split(", ")
for i in range(0, len(x)):
x[i] = int(x[i])
k = 2
clusters, centroids = kmeans1d.cluster(x, k)
print(clusters) # [1, 0, 0, 0, 0] sample result sent to arduino
ser.write(clusters)
import serial
import time
arduino = serial.Serial('COM4', 115200, timeout=.1)
time.sleep(2);#time for serial port to open
count = 0
prevTime = time.time()
while True:
if time.time() - prevTime > 1.0:
prevTime = time.time()
if count == 0:
count = 1
message= "[1, 0, 0, 0, 0]"
newMessage = message.encode()
arduino.write(newMessage)
elif count == 1:
count = 0
message= "[0, 0, 0, 0, 1]"
newMessage = message.encode()
arduino.write(newMessage)
#read echo back from arduino verify receipt of message
data = arduino.readline()[:-2] #the last bit gets rid of the new-line char
if data:
print (data.decode('UTF-8'))#eliminate the 'b' bytes indicator