0

I have this code taking data over serial from an Arduino. I want to be able to perform math on the data coming off and then send the data to the server but and changed to the data results in a TypeError. I am trying to make this code work primarily in Python3.6.

import socket
import serial
from time import sleep

IP = "192.168.1.1"
PORT = 3553

ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
print(ser.name)

while True:

    data = str(str(ser.read(7))[2:9].replace("r","").replace("n","").replace("\\","")).split(",")
#   data = str(ser.read(7))
    line = ser.readline()

    clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    clientSock.sendto(data[0], (IP, PORT))

Here is the error.

$ sudo python3.6 udp_client.py
/dev/ttyUSB0
Traceback (most recent call last):
  File "udp_client.py", line 18, in <module>
    clientSock.sendto(data[0], (IP, PORT))
TypeError: a bytes-like object is required, not 'str'

Someone said this is a possible duplicate of this link but the most voted answer works only in Python2 and I had seen this question before and none of its answers solve my issue.

  • Possible duplicate of [TypeError: a bytes-like object is required, not 'str'](https://stackoverflow.com/questions/33003498/typeerror-a-bytes-like-object-is-required-not-str) – Steffen Ullrich Apr 02 '18 at 03:51

1 Answers1

0

socket can only send bytes-like object. Your data is str, so you should encode it to bytes by some means.
Try to replace the first str in this line:

data = str(str(ser.read(7))...

into bytes and run it again.

data = bytes(str(ser.read(7))...

This use UTF-8 as default encoding type.

Hou Lu
  • 3,012
  • 2
  • 16
  • 23