[FIXED] Python & Arduino communication - TypeError: must be real number, not str

Issue

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]

Solution

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
Answer Checked By - Terry (Python.Easybugfix Volunteer)

Related Posts

Post a Comment