Saturday, June 25, 2016

Serial Communication Using Python

Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. The language provides constructs intended to enable clear programs on both a small and large scale.

Python supports multiple programming paradigms, including object-oriented,imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.

Python interpreters are available for many operating systems, allowing Python code to run on a wide variety of systems. Using third-party tools, such as Py2exe or Py installer, Python code can be packaged into stand-alone executable programs for some of the most popular operating systems, so Python-based software can be distributed to, and used on, those environments with no need to install a Python interpreter.


We won't go in much details, as an Embedded Electronics Engineer serial communication is important to us and in the following section we will see how we can achieve this. The code provided below is self explanatory and can be used as base to do serial communication in Python with your embedded device.

Python doesn't have any library for serial communication, so before proceeding further we have to install the PySerial package, which can be done easily with the help of few commands.

For Python 3.x:
  • Open Command Prompt and type
    pip3 install pyserial
    This command will download and install the PySerial package from internet.
Install PySerial for Python 3.x
 For Python 2.7.x:
  • Open Command Prompt and type
    pip install pyserial
    This command will download and install the PySerial package from internet.

Install PySerial for Python 2.7.x

Once the PySerial package is installed, open the python GUI (IDLE) and type the command "import serial", if it doesn't give any error, then it means PySerial library is successfully installed.

Get the List of available Serial Ports:
To get the list of available serial ports, use the following commands from the python terminal and it will gives you the list of all available serial ports on your PC.
Python 3.x:

>>> import serial.tools.list_ports as port_list
>>> ports = list(port_list.comports())
>>> for in ports: print (p)

COM2 - Communications Port (COM2)
COM1 - ELTIMA Virtual Serial Port (COM1->COM5)
COM5 - ELTIMA Virtual Serial Port (COM5->COM1)
COM3 - ELTIMA Virtual Serial Port (COM3->COM6)
COM6 - ELTIMA Virtual Serial Port (COM6->COM3)
COM4 - ELTIMA Virtual Serial Port (COM4->COM7)
COM7 - ELTIMA Virtual Serial Port (COM7->COM4)

>>> 
List of Ports in Python 3
 Python 2.7.x:

>>> import serial.tools.list_ports as port_list
>>> ports = list(port_list.comports())
>>> for p in ports: print p

COM2 - Communications Port (COM2)
COM1 - ELTIMA Virtual Serial Port (COM1->COM5)
COM5 - ELTIMA Virtual Serial Port (COM5->COM1)
COM3 - ELTIMA Virtual Serial Port (COM3->COM6)
COM6 - ELTIMA Virtual Serial Port (COM6->COM3)
COM4 - ELTIMA Virtual Serial Port (COM4->COM7)
COM7 - ELTIMA Virtual Serial Port (COM7->COM4)

>>> 
List of Ports in Python 2.7.x

The following video will demonstrate the results of the code given below.

import serial
#Can be Downloaded from this Link
#https://pypi.python.org/pypi/pyserial

#Global Variables
ser = 0

#Function to Initialize the Serial Port
def init_serial():
    COMNUM = 1          #Enter Your COM Port Number Here.
    global ser          #Must be declared in Each Function
    ser = serial.Serial()
    ser.baudrate = 9600
    ser.port = COMNUM - 1   #COM Port Name Start from 0
   
    #ser.port = '/dev/ttyUSB0' #If Using Linux

    #Specify the TimeOut in seconds, so that SerialPort
    #Doesn't hangs
    ser.timeout = 10
    ser.open()          #Opens SerialPort

    # print port open or closed
    if ser.isOpen():
        print 'Open: ' + ser.portstr
#Function Ends Here
       

#Call the Serial Initilization Function, Main Program Starts from here
init_serial()

temp = raw_input('Type what you want to send, hit enter:\r\n')
ser.write(temp)         #Writes to the SerialPort

while 1:    
    bytes = ser.readline()  #Read from Serial Port
    print 'You sent: ' + bytes      #Print What is Read from Port
   

If you want to use Serial Communication using Python in Linux or on Raspberry Pi, then click here. This tutorial is written for Raspberry Pi and will work for Linux OS.


23 comments:

  1. For a beginner, knowing where to get pyserial from is not enough. What is the actual name of the file, and what do you do with it, if by chance you download the right one?

    ReplyDelete
  2. Hey Russ Puskaricik, i will try to explain in simple terms.
    In short Pyserial module contains the serial functions to be used for serial communication in python, without this you have to write your own drivers for serial communication,.
    To download the correct module, always follow the website and download the latest version.

    ReplyDelete
  3. I downloaded the module to my desktop. What do I do with it?
    st.py", line 1, in
    import serial
    ImportError: No module named 'serial'
    >>>

    ReplyDelete
  4. Hi Dan Hillsberry
    To me it looks that you haven't installed the pyserial module, that's why you are getting this error.
    Please install it and try again. By

    ReplyDelete
  5. hello sir , iam using an instrument which uses RS232 serial , and has its own set of commands( not SCPI) can i control it via python through pySerial?

    ReplyDelete
    Replies
    1. If it's not com port, then you can't use pyserial.
      What is the interface you are using, how you are connecting your device with PC, by which interface/port.
      If it's usb, then which class?

      Delete
  6. Hello Sir
    i want to communicate between 2 USB-RS485 convertor Module in LINUX os using pyserial, Can U plz explain me how to code with it using pyserial..??

    ReplyDelete
    Replies
    1. The code will remain same.
      RS485 is just an interface and is exactly similar to RS232 except the voltage levels.
      Just test this code i am sure it will work.

      Delete
  7. Hi
    i am getting below error for same code:
    Traceback (most recent call last):
    File "D:\New folder\Serial.py", line 29, in
    init_serial()
    File "D:\New folder\Serial.py", line 13, in init_serial
    ser.port = COMNUM - 1 #COM Port Name Start from 0
    File "C:\Python27\lib\site-packages\serial\serialutil.py", line 264, in port
    raise ValueError('"port" must be None or a string, not {}'.format(type(port)))
    ValueError: "port" must be None or a string, not

    ReplyDelete
  8. Hi,
    i am gettin below error
    Traceback (most recent call last):
    File "D:\New folder\Serial.py", line 29, in
    init_serial()
    File "D:\New folder\Serial.py", line 13, in init_serial
    ser.port = COMNUM - 1 #COM Port Name Start from 0
    File "C:\Python27\lib\site-packages\serial\serialutil.py", line 264, in port
    raise ValueError('"port" must be None or a string, not {}'.format(type(port)))
    ValueError: "port" must be None or a string, not

    ReplyDelete
    Replies
    1. Update the value of COMNUM, to the com port which you are using.
      If you still face any problem please share your program with me at matlab.academy@gmail.com
      And also share the snapshot of your device manager, listing which com port you are using.

      Delete
    2. how to update value of COMNUM ? Device manager Port : Silicon Labs CP210x USB to UART Bridge (COM3)

      Delete
    3. I'm facing the same problem
      even after updating the value of the COMNUM

      Delete
  9. Hello, I do have Pyserial installed but it still says that:

    ImportError: No module named serial

    Even tho I have it all installed...

    ReplyDelete
    Replies
    1. This message clearly indicates that pyserial is not installed.
      Are you running multiple versions of python on same machine??
      Are you using Windows Machine or Linux Based Machine??

      For Windows:
      Python2
      pip2 install pyserial
      Python3
      pip3 install pyserial

      Make sure that pip2/pip3 is added in PATH environment variables.

      Delete
  10. Hello, I need this for my College project but Im stuck with this:

    ImportError: No module named serial

    Even tho I have installed this : pyserial-3.4-py2.py3-none-any.whl

    What am I doing wrong?

    ReplyDelete
    Replies
    1. This message clearly indicates that pyserial is not installed.
      Are you running multiple versions of python on same machine??
      Are you using Windows Machine or Linux Based Machine??

      For Windows:
      Python2
      pip2 install pyserial
      Python3
      pip3 install pyserial

      Make sure that pip2/pip3 is added in PATH environment variables.

      Delete
  11. this code is written to send string data, i want to send 8 bits of binary data. can i do that using this code

    ReplyDelete
  12. hai sir
    when run the above code i was getting below error

    Traceback (most recent call last):
    File "/home/81c943aa8924f2cbfd8c44a719359319.py", line 32, in
    init_serial()
    File "/home/81c943aa8924f2cbfd8c44a719359319.py", line 14, in init_serial
    serial = serial.Serial()
    AttributeError: 'int' object has no attribute 'Serial'

    how can i resolve
    can you please answer that qustion

    ReplyDelete
  13. hi, i have this error when installing the Library :
    'pip' is not recognized as an internal or external command, operable program or batch file.

    ReplyDelete
  14. hi, i have this error when installing the Library :
    'pip' is not recognized as an internal or external command, operable program or batch file.

    heres my path when i open the cmd : C:\Documents and Settings\ALLS

    thank you

    ReplyDelete