TypeError: unicode strings are not supported, please encode to bytes: '\x08'

I read this answers:

But I was not understanding it. In my case I have chr(code) going into the serial.write functions.

Do I write b'chr(8)'?

import serial
import pygame
from pygame.locals import *


class RCTest(object):
def __init__(self):
    pygame.init()
    screen = pygame.display.set_mode((400, 300))
    self.ser = serial.Serial('COM3', 9600, timeout = 1)
    self.send_inst = True
    self.steer()

def steer(self):

    while self.send_inst:

        for event in pygame.event.get():
            print("entered for loop")

            if event.type == KEYDOWN:
                print("entered event.type == KEYDOWN")

                key_input = pygame.key.get_pressed()
                print("pygame.key.get_pressed() running")

                # complex orders
                if key_input[pygame.K_UP] and key_input[pygame.K_RIGHT]:
                    print("Forward Right")
                    self.ser.write((chr(6))

                elif key_input[pygame.K_UP] and key_input[pygame.K_LEFT]:
                    print("Forward Left")
                    self.ser.write((chr(4))

                # simple orders
                elif key_input[pygame.K_UP]:
                    print("Forward")
                    self.ser.write((chr(8))

                elif key_input[pygame.K_DOWN]:
                    print("Reverse")
                    self.ser.write((chr(2))

                # exit
                elif key_input[pygame.K_x] or key_input[pygame.K_q]:
                    print('Exit')
                    self.send_inst = False
                    self.ser.write((chr(0))
                    self.ser.close()
                    break

            elif event.type == pygame.KEYUP:
                self.ser.write((chr(0))


if __name__ == '__main__':
    RCTest()

After running the program, I press DOWN ARROWKEY.

entered for loop
entered for loop
entered for loop
Traceback (most recent call last):
entered event.type == KEYDOWN
  File "C:/Users/../rc_control_test.py", line 58, in <module>
pygame.key.get_pressed() running
    RCTest()
Reverse

1 answer

  • answered 2017-10-11 10:22 Daniel Lee

    to encode to bytes:

    "string".encode()
    >> b'string'
    

    Therefore, you can probably write like this:

    self.ser.write(("string".encode()))
    

    Else, if you want to write one character at a time:

    self.ser.write("A".encode())