Tuesday, June 2, 2015

Interfacing Arduino using Python

We know that Arduino IDE has inbuilt serial monitor. Using this serial monitor we can communicate with arduino and make arduino behave as we wanted. This serial monitor can be even built using python. This post is to show how to install PySerial and use it with arduino.

First of all download Python and install it (Python 2.7 recommended).

Python 2.7 Download

 Just by installing Python we cannot start programming. A script editor is also needed. There is a list of script editors available here. I use Geany.

List of Script Editors Python

The next step is to download Pyserial and  install it.

Pyserial Download

Download the tar.gz file and extract it. Then open the command prompt try typing python if you get a error message then follow these steps.

  • Right click Computer-Properties
  • Click change settings on the right hand side
  • Go to Advanced tab. Click Environment variables.
  • Double click Path and after a semicolon specify the path where python is installed
                       
  • Now restart the computer for the settings to get applied.
  • After restarting, open the command prompt and try typing python
  • Python terminal should open.
  • Now go to the extracted folder in the command prompt and type 
                                      python setup.py install

Installation will take place...

Now lets write a code to demonstrate the working of Pyserial.
This program switches ON and OFF the inbuilt led on the Arduino board.

Python Code:
 import serial  
 ser=serial.Serial("COM31",9600)   #start a serial connection  
 a='0'  
 while a=='1' or a=='0':  
      a=raw_input()               #get the input  
      if a=='1' or a=='0':  
           ser.write(a)             #write to serial  
           print ser.readline()       #read a line from the serial  
      else:  
           break  


Arduino code:

  #include<Serial.h>  
    void setup()  
    {  
     Serial.begin(9600);  
     pinMode(13,OUTPUT);  
    }  
    char a;  
    void loop()  
    {  
     if(Serial.available())  
     {  
      a=Serial.read();  
      if(a=='1')  
      {  
       digitalWrite(13,HIGH);  
       Serial.write("ON\n");  
      }  
      else if(a=='0')  
      {  
       digitalWrite(13,LOW);  
       Serial.write("OFF\n");  
      }  
     }  
    }  
  

The result will look like this:



#IIE

No comments:

Post a Comment