Skip to content
Advertisement

Python Error: ‘TypeError: a bytes-like object is required, not ‘str” for Robot Controller using UDP Protocol

I was trying to make a keyboard-based controller for my robot using the UDP protocol to send packets of keypresses to an ESP8266 NodeMCU microcontroller using Python. When I wrote this code, the following error appeared:

C:UsersCHUCHDesktopPython and ArduinoledvenvScriptspython.exe" "C:/Users/CHUCH/Desktop/Python and Arduino/led/main.py" 
pygame 2.0.2 (SDL 2.0.16, Python 3.9.2)
Hello from the pygame community. pygame.org/contribute.html 
Traceback (most recent call last):
  File "C:UsersCHUCHDesktopPython and Arduinoledmain.py", line 23, in <module> 
    main() 
  File "C:UsersCHUCHDesktopPython and Arduinoledmain.py", line 19, in main 
    sock.sendto("Q", (my_ip, my_port))
TypeError: a bytes-like object is required, not 'str'
Process finished with exit code 1

This is the code:

import socket

import KeyPressModule as Key

my_ip = 'Use your IP'
my_port = 8080

Key.init()
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

def main():
    if Key.get_Key('UP'):
        sock.sendto('u', (my_ip, my_port))
    elif Key.get_Key('DOWN'):
        sock.sendto('d', (my_ip, my_port))
    elif Key.get_Key('LEFT'):
        sock.sendto('l', (my_ip, my_port))
    elif Key.get_Key('RIGHT'):
        sock.sendto('r', (my_ip, my_port))
    else:
        sock.sendto('q', (my_ip, my_port))

if __name__ == '__main__':

    while True:
        main()

Advertisement

Answer

You got this error because the method you’re calling expects a bytes object. This makes sense, since UDP packets consists of bytes. They do not have any notion of the meaning of those bytes, i.e. if they are text or images or something else.

If you want to send text using a byte-based protocol, you have to encode it.

In your case, since you seem to be sending one character at a time and you’re using string literals, the easiest solution is to add a b before the letters you want to send, so b'u' instead of 'u':

if Key.get_Key('UP'):
    sock.sendto(b'u', (my_ip, my_port))
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement