我读了这个答案:
但我不理解它。在我的情况下,我chr(code)
进入serial.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()
运行程序后,我按下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
答案 0 :(得分:1)
编码为字节:
"string".encode()
>> b'string'
因此,您可以这样写:
self.ser.write(("string".encode()))
否则,如果你想一次写一个字符:
self.ser.write("A".encode())