0
votes

So I have a code that reads the incoming serial data from the Arduino and also writes serial data when specific keys are pressed, I also want to write this incoming serial data to the text file and I am using threading. This is the code:

from pynput import keyboard
import threading
import serial
import sys
import io




class SerialReaderThread(threading.Thread):

    ser = None
    def run(self):
        global ser

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

        while True:
            print(ser.readline().decode('utf-8'))


class FileWriting(threading.Thread):



   def run(self):

       global ser    

       while True:

            with io.open("output.txt", "a", encoding="utf-8") as f:
                f.write(ser.readline().decode('utf-8'))


class KeyboardThread(threading.Thread):

    def run(self):
        global ser
        def on_press(key):
            global ser
            try:
                format(key.char)


                if key.char == "1":
                    ser.write(b'1\r\n') #serial write - 1

                elif key.char == "2":
                    ser.write(b'2\r\n') #serial write - 2

                elif key.char == "3":
                    ser.write(b'3\r\n') #serial write - 3

                elif key.char == "4":
                    ser.write(b'4\r\n') #serial write - 4

                elif key.char == "5":
                    ser.write(b'5\r\n') #serial write - 5    

                elif key.char == "6":
                    ser.write(b'6\r\n') #serial write - 6

                elif key.char == "0":
                    ser.write(b'0\r\n') #serial write - 0      
            except AttributeError:
                print(''.format(key))





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

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

serial_thread = SerialReaderThread()
keyboard_thread = KeyboardThread()
file_thread = FileWriting()


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

Now my problem is that I cannot write to the file, the reading serial data works perfectly and the writing to the Arduino also works perfectly, however when I try to additionally write to the file it gives me this error.

    Exception in thread Thread-3:
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\menucode.py", line 33, in run
    f.write(ser.readline().decode('utf-8'))
NameError: name 'ser' is not defined

Any help will be appreciated, thanks alot.

1
put ser = serial.Serial('COM4', baudrate = 9600, timeout = 20), at the top of your code just after imports and remove all the othersHouda

1 Answers

0
votes

global variables are usually initialised at the outermost level, so move your ser = None to line 6. (Your use inside the class is making ser a class variable, not a global.) You don't need to declare global ser except in a code block where you are going to change its value. So remove all of them except the one before ser = serial.Serial....