Ok first I convert this code to pep8 style guide.
ser = serial.serial('COM3', '9600')
def SendCommandV1(ser, command_string):
ser.write(command_string)
def SendCommandV2(command_string):
ser.write(command_string)
SendCommandV1('ser, Hello World')
SendCommandV2('Hello World') #is this OK?
To this:
from serial import Serial
# Serial is a class
# Functions: lower_case_whitespace_by_underscore
# Function are verbs, so send_command is a good choice
def send_command_v1(serial_connection, command_string):
serial.write(serial_connection)
# bad example. this function fails, if you use
# it in another module and forgot, that you don't
# have ser
def send_command_v2(command_string):
ser.write(command_string)
# there was a quote before ser, this was wrong
# use double quotes where you can. Why? You can see them better
# A IDE can also help to see the difference with syntax highlighting
# ser was too far away from usage
ser = Serial("COM3", 9600)
# baudrate, the 2nd parameter, should be an int and not a str
send_command_v1(ser, "Hello World")
If this is a throw away script, it's too complicated.
from serial import Serial
with Serial('COM3', 9600) as ser:
ser.write("Hello World")
A function which just pass through a string to a method is not very useful.
If this function does send a predefined command, then it's useful.
def send_shutdown(serial_connection):
serial_connection.write(b"SHUTDOWN\n")
If you don't like to pass through always the serial_connection object, then object-oriented programming is the solution.
#!/usr/bin/env python3
# for windows users this shebang is useless
# for *nix (linux, mac, bsd) it's common to have a shebang
from serial import Serial
class SerialCommander:
"""
The SerialCommander can send greet and shutdown.
"""
def __init__(self, port, baudrate):
"""
Connect to a serial port with given baud rate.
On Windows systems, use: COM3 or COM4
On Linux Systems there are different variations
"""
self.connection = Serial(port, baudrate)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# if an exception happened in the with-block,
# then the arguments have a meaing.
# we use it just to close the connection
self.connection.close()
def greet(self):
self.connection.write(b"Hello World\n")
def shutdown(self):
self.connection.write(b"SHUTDOWN\n")
def main()
"""
Main program
"""
# SerialCommander(...) calls __init__ and an instance is returned
# then with calls __enter__ which just returns self, which is the same object
# this returned instance is assigned to commander
with SerialCommander("COM4", 9600) as commander:
# calling methods on SerialCommander instance
# commander is the name, where the created instance (object) points to
commander.greet()
commander.shutdown()
# leaving the with block, calls __enter__ of the instance commander
# calls main only if this module was not imported
# it's only called, if you run this as a script
if __name__ == "__main__":
main()