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.
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:
For Python 2.7.x:
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 |
- 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 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)
>>>
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)
>>>
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 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 3 |
>>> 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
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?
ReplyDeleteyou have to extract it and install.
DeleteHey Russ Puskaricik, i will try to explain in simple terms.
ReplyDeleteIn 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.
I downloaded the module to my desktop. What do I do with it?
ReplyDeletest.py", line 1, in
import serial
ImportError: No module named 'serial'
>>>
Instal pySerial Library
DeleteHi Dan Hillsberry
ReplyDeleteTo 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
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?
ReplyDeleteIf it's not com port, then you can't use pyserial.
DeleteWhat 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?
Hello Sir
ReplyDeletei 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..??
The code will remain same.
DeleteRS485 is just an interface and is exactly similar to RS232 except the voltage levels.
Just test this code i am sure it will work.
Hi
ReplyDeletei 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
Hi,
ReplyDeletei 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
Update the value of COMNUM, to the com port which you are using.
DeleteIf 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.
how to update value of COMNUM ? Device manager Port : Silicon Labs CP210x USB to UART Bridge (COM3)
DeleteI'm facing the same problem
Deleteeven after updating the value of the COMNUM
Hello, I do have Pyserial installed but it still says that:
ReplyDeleteImportError: No module named serial
Even tho I have it all installed...
This message clearly indicates that pyserial is not installed.
DeleteAre 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.
Hello, I need this for my College project but Im stuck with this:
ReplyDeleteImportError: No module named serial
Even tho I have installed this : pyserial-3.4-py2.py3-none-any.whl
What am I doing wrong?
This message clearly indicates that pyserial is not installed.
DeleteAre 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.
this code is written to send string data, i want to send 8 bits of binary data. can i do that using this code
ReplyDeletehai sir
ReplyDeletewhen 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
hi, i have this error when installing the Library :
ReplyDelete'pip' is not recognized as an internal or external command, operable program or batch file.
hi, i have this error when installing the Library :
ReplyDelete'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