Python & Arduino communication – TypeError: must be real number, not str

Question:

I want to use the kmeans1d library to cluster some values from an Arduino, however, I got a TypeError from Python.

Below is the Arduino code:

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("100, 150, 300, 130, 140");
  delay(5000);
}

Python code:

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]
Asked By: Ykh Yeung

||

Answers:

You are passing a string where a number is expected.

Try something like this:

x = r1.decode('utf8').rstrip().split(", ")
for i in range(0, len(x)): 
    x[i] = int(x[i]) 
Answered By: ocrdu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.