序列号。串行读取期间无法进行任何输入

PySerial. Unable to make any input during serial reading

所以,我正在尝试通过使用 pyserial 库使用 python 与 Arduino 进行串行通信。我有一个真正的循环,我正在读取从 Arduino 发送的数据,但是,我希望能够通过使用 ser.write 从 Arduino 发送一些东西,但是,我无法这样做。

import serial
import sys
import time
import pynput


from pynput import keyboard


ser = serial.Serial('COM4', baudrate = 9600, timeout = 20)





while True:

        print(ser.readline().decode('utf-8'))






def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        return False


with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

listener = keyboard.Listener(
    on_press=on_press,
    on_release=on_release)
listener.start()

我也在使用 pynput 库来查找键盘上按下的键,稍后我将修改这些键,例如,如果按下键 0 ser.write 等等。我就是无法让它工作所以它会打印我按下的任何键,它总是在等待 ser.readline。有人可以帮我解决这个问题吗?

总而言之,我希望能够在串口读取时输入一些密钥。

谢谢

你的问题基本上是 while True 循环下面的代码永远不会执行,因为循环永远不会结束。 所以你基本上必须使用一种叫做线程的东西,你把你的过程分成几个部分,运行 这些部分在单独的线程中。 您可以在下面看到一个线程示例,您可以按原样使用它。 KeyboardThread 处理所有键盘输入,而 SerialReaderThread 处理串行读取调用。

from pynput import keyboard
import threading
import time
import serial
import sys

class SerialReaderThread(threading.Thread):
    def run(self):
        ser = serial.Serial('COM4', baudrate = 9600, timeout = 20)
        while True:
            print(ser.readline().decode('utf-8'))

class KeyboardThread(threading.Thread):
    def run(self):
        def on_press(key):
            try:
                print('alphanumeric key {0} pressed'.format(key.char))

                # quit when q is pressed
                if key.char == "q":
                    exit()
            except AttributeError:
                print('special key {0} pressed'.format(key))

        def on_release(key):
            print('{0} released'.format(
                key))
            if key == keyboard.Key.esc:
                return False


        with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
            listener.join()

        listener = keyboard.Listener(on_press=on_press, on_release=on_release)
        listener.start()

serial_thread = SerialReaderThread()
keyboard_thread = KeyboardThread()

serial_thread.start()
keyboard_thread.start()
serial_thread.join()
keyboard_thread.join()

您可以在此处了解有关线程及其使用方法的更多信息:https://www.tutorialspoint.com/python3/python_multithreading.htm

所以我修改了 vincentscode 提供的代码,只需添加选项以串行写入代码中星号指示的内容。现在由于某种原因我遇到了很多错误。我尝试了 运行 相同的代码,但省略了 SerialReaderThread,它与串行写入功能一起工作得很好,但不能一起工作。

from pynput import keyboard
import threading
import time
import serial
import sys

class SerialReaderThread(threading.Thread):
    def run(self):
        ser = serial.Serial('COM4', baudrate = 9600, timeout = 20)
        while True:
            print(ser.readline().decode('utf-8'))

class KeyboardThread(threading.Thread):
    def run(self):
        def on_press(key):
            try:
                print('alphanumeric key {0} pressed'.format(key.char))


                if key.char == "3":
                    **ser.write(b'3\r\n') #serial write - 3**
            except AttributeError:
                print('special key {0} pressed'.format(key))

        def on_release(key):
            print('{0} released'.format(
                key))
            if key == keyboard.Key.esc:
                return False


        with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
            listener.join()

        listener = keyboard.Listener(on_press=on_press, on_release=on_release)
        listener.start()

serial_thread = SerialReaderThread()
keyboard_thread = KeyboardThread()

serial_thread.start()
keyboard_thread.start()
serial_thread.join()
keyboard_thread.join()

error

粘贴为代码时出错:

Unhandled exception in listener callback
Traceback (most recent call last):
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pynput\_util\__init__.py", line 162, in inner
    return f(self, *args, **kwargs)
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pynput\keyboard\_win32.py", line 280, in _process
    self.on_press(key)
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pynput\_util\__init__.py", line 78, in inner
    if f(*args) is False:
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\project\koko.py", line 21, in on_press
    ser.write(b'3\r\n')
NameError: name 'ser' is not defined
Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\project\koko.py", line 33, in run
    listener.join()
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pynput\_util\__init__.py", line 210, in join
    six.reraise(exc_type, exc_value, exc_traceback)
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\lib\site-packages\six.py", line 702, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pynput\_util\__init__.py", line 162, in inner
    return f(self, *args, **kwargs)
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pynput\keyboard\_win32.py", line 280, in _process
    self.on_press(key)
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pynput\_util\__init__.py", line 78, in inner
    if f(*args) is False:
  File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\project\koko.py", line 21, in on_press
    ser.write(b'3\r\n')
NameError: name 'ser' is not defined

我不知道可能是什么问题...

编辑:我通过搜索堆栈溢出找到了解决方案,只是在开始时将 ser 声明为 None,如 ser = None,然后在每个 [=23] 中将 ser 声明为全局变量=] 只写 global ser.