Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending data over serial in python from different functions

I program in C++ and C# normally and am trying to get accustomed to how python works so forgive me if this is a fairly basic question.

I'd like to open a serial connection in python over RS-232 and send data from various functions. Here's the functions that I have to open a serial port and send data:

def sendData(data):
    ser = serial.Serial('/dev/ttyUSB0', 115200)
    data += "\r\n"
    ser.write(data.encode())

Pretty simple, but I'd like to move the ser = serial.Serial('/dev/ttyUSB0', 115200) line outside the function so that I can just call this function on it's own.

Now in other languages I would just make the ser variable public so that other functions could access it, but I'm not sure I'm understanding how variables work in python properly yet. Ideally I'd like something like this:

def main():
    ser = serial.Serial('/dev/ttyUSB0', 115200)
    while 1:
        #misc code here
        sendData(data)

I know I could pass the ser variable through the function call and make it sendData(ser, data), but that seems unnecessary. What's the best way to do this?

Thanks!

like image 661
Xander Luciano Avatar asked Oct 28 '25 12:10

Xander Luciano


1 Answers

You can use the global keyword in your main function to assign the public variable:

ser = None

def sendData(data):
    data += "\r\n"
    ser.write(data.encode())

def main():
    global ser
    ser = serial.Serial('/dev/ttyUSB0', 115200)
    while 1:
        #misc code here
        sendData(data)

Or even better, using a class:

class SerialWrapper:
    def __init__(self, device):
        self.ser = serial.Serial(device, 115200)

    def sendData(self, data):
        data += "\r\n"
        self.ser.write(data.encode())

def main():
    ser = SerialWrapper('/dev/ttyUSB0')
    while 1:
        #misc code here
        ser.sendData(data)
like image 196
fips Avatar answered Oct 30 '25 01:10

fips



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!