Python & auduino communication - TypeError: must be real number, not str

Python & auduino communication - TypeError: must be real number, not str

我想使用 kmeans1d 对来自 arduino 的一些阀门进行聚类,但是我从 python 得到了 TypeError。

下面的arduino代码:

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("100, 150, 300, 130, 140");
  delay(5000);
}

python代码:

import kmeans1d
import serial
import time

ser = serial.Serial('/dev/ttyACM0',9600)
r1=ser.readline()
#x = [100, 110, 130, 103, 102]
x = [r1.decode('utf-8')]
k = 2
clusters, centroids = kmeans1d.cluster(x, k)
print(clusters)   # [1, 1, 1, 0, 3, 3, 3, 2, 2, 2]

您正在传递一个需要数字的字符串。

尝试这样的事情:

x = r1.decode('utf8').rstrip().split(", ")
for i in range(0, len(x)): 
    x[i] = int(x[i])