Quantcast
Channel: xanthium enterprises - robotics and embedded system for all
Viewing all articles
Browse latest Browse all 134

Cross Platform serial communication using Python (PySerial) and Arduino

$
0
0

Tutorial on programming the serial port using python and pyserial on Linux,windows and mac os X

Tutorial on connecting an Arduino or Microcontroller (AVR ATmega328P,MSP430 ,PIC) with a Linux/Windows PC using serial port (VCP). and communicating with it using Python and PySerial library.

This tutorial will concentrate on Python 3.x.x language and will use Pyserial 3.4 Library.

First section deals with Arduino and Second section deals with bare microcontrollers like AVR,Microchip and Last section deals with Linux specific details.

Index

  1. Introduction
  2. pySerial Module
  3. Sourcecodes
  4. Hardware used 
  5. Python on Windows
  6. Installing PySerial on Windows 
  7. Writing data to Serial Port 
  8. Running the Code on Windows
  9. Pyserial Exceptions
  10. Reading Data from Serial port 
  11. Interfacing Microcontroller with PC
  12. Interfacing MSP430 with PC
  13. Interfacing ATmega328P with PC
  14. DTR RTS Pin Control using Pyserial
  15. Python Linux Serial Programming

 

Introduction

Python is an open source, cross platform ,interpreted language that is easy to learn for beginners. One of the many advantages of Python is the sheer number of contributed modules for performing a wide variety of tasks.It is widely used for building scripts/program to interact with real world objects like USB relays,USB data acquisition devices,USB data loggers and other embedded systems.

Easiest way to interact with serial port devices is over a Virtual Com Port using a USB to Serial Converter IC like

  • FTDI FT232RL
  • TUSB3410
  • or CP2102.

Once the necessary drivers are installed you can interact over VCP by reading and writing into it.

One problem with developing code that uses serial port is portability, you can't use the same code in both Windows and Linux. For each operating system (Windows/Linux) you have to write custom codes using the native API's as we have done

 

pySerial Module

Python provides an easy way to do cross platform serial communication using pySerial module.

The modules hides all the OS specific peculiarities and presents a uniform simple interface for programming the serial port. The code written with pySerial can run unmodified on Windows and Linux systems

 

Sourcecodes

link to xanthium enterprises repo on Github containing code for cross platform serial communication using Python and Pyserial  

 

 

 

 

Hardware Used 

Buy USB to RS485 converter online from here   

Buy USB to RS485 converter online from here (made in India )

USB2SERIAL - Any easy to use multi protocol converter that can convert from USB to RS485/RS232/Serial.The Board comes with selectable voltage levels for interfacing with 5V and 3.3V logic families.It has screw terminals  for easy access to FT232RL pins .3 Pin RS232 and DB9 Male pin for RS232 protocols.

 

Python on Windows

In Windows, Python is not installed by default, you can find python binary installers from either python.org or from ActiveState software.

After completing the installation you can type “python” on your command prompt to enter the python shell. (use CTRL + Z to exit from the shell).

python 3.0 running on windows7

or use GUI based shell IDLE.

python IDLE running on windows 7

 

Installing PySerial on Windows 

After you have installed the python interpreter, You can install PySerial using pip installer.Earlier Pyserial Homepage used to provide Windows Executable file which can be installed using point and click method .Now they are providing source and wheels package only.

Here we will be installing the PySerial Package using pip installer.So open up your Windows Command prompt and type in the following command.

C:\python -m pip install pyserial

as shown below 

installing pyserial using pip on Windows 7
After installing pySerial, open the python shell and type “import serial”.

If you are not getting any error messages, pySerial is installed properly.

Some IDE's like Thonny has built in Python interpretors which work independently from the interpreter installed on your system.

using thonny for python serial port programming with arduino

The IDE already has pySerial installed and there is no need for installing it using pip command.

python thonny pyserial installation list

 

Writing data to Serial Port using Python and pySerial

Now lets open a serial port and write some values to it. The code in python is quite straight forward, you can just read it like plain English.

Open a text editor and type the following lines of code into it .Save the file with a ” .py” extension.

The Below code writes character 'A' to the serial port.

# Python code transmits a byte to Arduino /Microcontroller

import serial

import time

SerialObj = serial.Serial('COM24') # COMxx   format on Windows
                                   # ttyUSBx format on Linux

SerialObj.baudrate = 9600  # set Baud rate to 9600
SerialObj.bytesize = 8     # Number of data bits = 8
SerialObj.parity   ='N'    # No parity
SerialObj.stopbits = 1     # Number of Stop bits = 1

time.sleep(3)

SerialObj.write(b'A')      #transmit 'A' (8bit) to micro/Arduino

SerialObj.close()          # Close the port

The first line import serial imports the pySerial module so that your program can use it.

ComPort = serial.Serial('COM24') opens the serial port named COM24.

 

In Windows,
Please give the COM number corresponding to your Serial port or USB to Serial Converter instead of COM24.

finding the COM port number in windows

 

 

Opening the serial port using pySerial may reset the Arduino connected on the port,(here COM24).This is specific to Arduino  only .

time.sleep(3)

So you should wait some time (here 3 seconds) before transmitting the data to the Arduino board.In the above code we are using time.sleep(3) function.

 

Serial communication occurs in bytes (8 bits) while Python3+ handles strings in unicode format which may consume upto 4 bytes.

So to make the characters suitable to send to a microcontroller we have to convert them to byte based chunks.

In the above Example we are sending a byte 'A'. Here A is defined as a byte by using b prefix.You can also use the bytearray() function.

SerialObj.write(b'A')      #transmit 'A' (8bit) to micro/Arduino

 

SerialObj.write(b'A' function then writes/sends data to your microcontroller /Arduino.

 

Running the Python Code

In Windows,
You can either run the code from command line,

D:\> python yourSerialTransmitCode.py

 

or by using IDLE
From IDLE use “File → Open” to open your code file and from “Run → Run Module”.

using IDLE to run python serial communication programs on windows

 

 

Arduino Side Code

PC and Arduino are connected as shown below using a single USB cable.

Python code not transmitting to Arduino resetting

On the Arduino side ,

we wait for the Character A and turns the LED connected to Pin12 ON for 2 seconds.

A switch() is used to select the required action.

The partial code is shown below.

if (Serial.available()
    {
      
      RxedByte = Serial.read();     
      switch(RxedByte)
      {
        case 'A'digitalWrite(12,HIGH);
                   delay(1000);
                   digitalWrite(12,LOW);
                   break;

        case 'B': //your code
                   break;
        default:
                   break;
      }//end of switch()
    }//endof if 

Please visit our Github for the full code

 

Pyserial Exceptions

Some times opening the serial port may fail due to various conditions like port in use ,port not found etc .

PySerial comes with the exception serial.SerialException which can be used to identify the error and fail gracefully. 

The below partial code shows how to use exceptions 

try:
    SerialObj = serial.Serial('COM11',9600) # open the Serial Port
    
    
exceptserial.SerialExceptionas var : # var contains details of issue
    print('An Exception Occured')
    print('Exception Details-> ', var)
    
else:
    print('Serial Port Opened')

Here is an example of the error message you will get

when some other process is using the port you are trying to access.

pyserial exception programming for serial port on windows linux and Mac

When Port number is wrong.  

python serial programming pserial exception port not found

%Run is due to the IDE running the code on the terminal

 

Reading Data from Serial port using Python and Pyserial

PySerial provides  two functions to read data from the serialport

  1. readline()
  2. read()

readline() reads till it encounters a newline character '\n'and returns the bytes it has read.If \n character is not encountered it will wait forever or until the read timeout expires.

Partial Python Code (PC side)

ReceivedString = SerialObj.readline()
print(ReceivedString)
SerialObj.close() 

Arduino Code

void loop()
{
  char TextToSend[] = "Hello From Arduino Uno";
  Serial.println(TextToSend); // sends a \n with text
  delay(1000);
}

 

The Arduino sends a string which is received by the PC side Python code and displayed on terminal.

Python script for receiving a string on Windows 10 PC

Please note that only relevant portions of the code are shown above.

Please visit our github repo for full code.

 

Connecting a Bare Microcontroller to your PC 's Serial port
 

In the above tutorial we learned how to connect an Arduino board with a PC and communicate with it (Receive/Transmit data ) using a standard USB cable.

What if instead of an Arduino we just want to connect a bare microcontroller like ATmega328P,ATmega16,MSP430 or PIC18F4550 to your PC.

In the case of Arduino all the details of how ATmega328P connects with the USB section is abstracted away from the user,when you are building embedded systems  you have to know which signals are connected to which.

When you are using a microcontroller which do not have any built in USB controller like ATmega16 or MSP430G2553 ,you have to use a USB to Serial Converter chip like FT232RL or buy a standard USB to serial converter board like  USB2SERIAL to convert serial signals to the USB ones.

Buy USB to RS485 converter online from here

The USB2SERIAL board shown can work as a USB to serial Converter,USB to  RS232 Converter or USB to RS485 converter

The below block diagram shows how to interface any microcontroller with  a standard USB to serial converter. 

block diagram showing connection between MSP430 UART and PC serial port or USB to serial converter

Here the TXD of the serial port is connected to the RXD of the microcontroller UART and vice versa. So when microcontroller transmits a byte it goes to the receive buffer of the serialport on the PC side and vice versa.

Ground lines are made common to both PC and microcontroller.

interfacing atmega328p with Pc using usb2serial and python for serial communication

 

MSP430 Microcontroller interface with PC using Python

null modem connection between msp430 launchpad and usb2serial

Above image shows how to hook up a launchpad board with PC using USB2SERIAL converter The Controller (MSP430G2553)  is connected to the FT232's Serial port using a null modem cable as shown in the above figure.

msp430 interfaced with PC using a FT232 usb to serial converter  and python

 

Please note that MSP430's are 3.3V microcontrollers ,so please select the IO voltage levels of USB2SERIAL board as 3.3V.

In case you want to know more about MSP430's, check this short tutorial on how to configure MSP430G2553 UART.

 

ATmega328P Microcontroller interface with PC using Python

Yes, Arduino uno is ATmega328P but here the code is written in AVR embedded C and compiled using AVR studio or Microchip Studio.

Bi directional asynchronous serial communication from Mac/PC to Atmega328p microcontroller

 

 
Controlling RTS and DTR pins in Python using PySerial
 
RTS and DTR pins are two extra lines available on most serial ports which are used for signaling purposes.They do not transmit serial data but are used for signalling purposes.You can make them HIGH or LOW to control a transistor switch or logic circuit. 
 
Earlier, PySerial API used SerialObj.setRTS() and SerialObj.setDTR()which are now deprecated.
 
The new simplified API is just
  1. rts
  2. and dtr
which can be set or cleared by assigning a 1 or 0.
 

import serial

SerialObj = serial.Serial('COM6',9600)

SerialObj.rts = 1#RTS HIGH
SerialObj.rts = 0#RTS LOW

SerialObj.dtr = 1#DTR HIGH
SerialObj.dtr = 0#DTR LOW

SerialObj.close()

Please note that you need to add delay between HIGH and LOW to visualise the transition.
In some USB to Serial Converter chips like FT232RL the signals are Active LOW,so setting the pin=1 would make the signal LOW.

 

Python Serial programming on Linux

 

 

 

 

 

 

 

 


Viewing all articles
Browse latest Browse all 134

Trending Articles