1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Small Example for pyserial using Threading

Discussão em 'Python' iniciado por Stack, Outubro 8, 2024.

  1. Stack

    Stack Membro Participativo

    Can anyone please give me a small and simple example on how to use threading with pyserial communication. I am googling for over three days and I am still illeterate and I dont even have a working piece of code which integrate both of them

    Basically I am aiming to use threading in this scenario:

    Have a serial communication continuously go on in the back ground to attain certain value (say A) from an MCU.

    Stop attaining value A - then attain value B...and start continuously attaining value A again.

    You can find some basic code here.

    import threading
    import time
    import sys
    import serial
    import os
    import time

    def Task1(ser):

    while 1:

    print "Inside Thread 1"
    ser.write('\x5A\x03\x02\x02\x02\x09') # Byte ArrayTo Control a MicroProcessing Unit
    b = ser.read(7)
    print b.encode('hex')
    print "Thread 1 still going on"
    time.sleep(1)


    def Task2(ser):

    print "Inside Thread 2"
    print "I stopped Task 1 to start and execute Thread 2"
    ser.write('x5A\x03\x02\x08\x02\x0F')
    c = ser.read(7)
    print c.encode('hex')
    print "Thread 2 complete"


    def Main():
    ser = serial.Serial(3, 11520)
    t1 = threading.Thread(target = Task1, args=[ser])
    t2 = threading.Thread(target = Task2, args=[ser])
    print "Starting Thread 1"
    t1.start()
    print "Starting Thread 2"
    t2.start()

    print "=== exiting ==="

    ser.close()

    if __name__ == '__main__':

    Main()

    Continue reading...

Compartilhe esta Página