*/ ?>

Introduction

Python is one of the most popular and most widely used programming languages today, and it is predicted that it will have even brighter future. What we are more interested in is that with it, you can "talk" to Croduino/Arduino via a simple serial interface. All UNIX systems can read and write serial devices and that job is greatly faciliated by pySerial Library.

Instalation:Python and pySerial

Before we start with serial port programming, let's install Python and pySerial. NOTE: In this tutorial, we will be using Python 2.7. If you want to use Python 3.x, you have a short tutorial on how to change the code, on the very end. Short tutorial on how to install .tar file: In the terminal, execute the following commands:
tar xfvz /Users/*username*/Downloads/pyserial-2.7.tar.gz
cd pyserial-2.7
sudo python setup.py install
If you're using Windows OS, download .msi file.

Arduino code

The first step is to make Croduino/Arduino to send data through the serial port. This is the same as when using the serial monitor, meaning we use Serial.print() function. We worked with several examples of the prints in the Serial Monitor, so we will use that. We will use HC-SR04 ultrasonic module, and how can be read in KKM tutorial. To begin with, let's connect module to Croduino/Arduino: We will make small changes in the code:
const int trig = 11;        // Trig on PIN11
const int echo = 12;        // Echo on PIN12
 
void setup() {
   
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
   
  Serial.begin(9600);  // starting serial communication
   
}
 
void loop() {
   
// since we are not using library, down below is written a way of communicating with module
   
  double time, distance;
   
  digitalWrite(trig, HIGH);   // Sending of a trig
  delayMicroseconds(10);      // Sent trig duration 10 μs = 0.1 ms
  digitalWrite(trig, LOW);
   
  time = pulseIn(echo, HIGH);        // Downloading of reflected trig
  distance = (time/2) / 28;         // Calculating the distance, in centimeters
                                    // final distance from sensor to subject
                                    // variable "distance" is in cm
     
  Serial.println(distance);  
  delay(50);  // recommended pause between readings shouldn't be less then 50ms 
}
Although the modifications are not necessary, we will adjust the code so we can continue new Crodiuno/Arduino and Python lessons in this tutorial. Before writing the script, it is important to remember which baud rate have we chosen, and where is our Croduino/Arduino port. The baud rate is entered during execution of Serial.begin() function, so let's find it in the code above:
Serial.begin(9800);
So, baud rate  9800 bits per second. pySerial can use a variety of standard and non standard rates, and a complete list can be found here. We have already talked on how to find a virtual COM port with Croduino/Arduino, and it can be found in tutorial on Arduino IDE. If you are more resourceful , you can use this Terminal: Mac OS X
ls /dev/tty.*
Linux
ls /dev/ttyUSB*

Python code

Python code can be written and executed in various ways, and we will use IDLE for simplicity of presentation. On Windows, can be found at: Start - All Programs - Python - IDLE. If you use OS X,  IDLE is located in Application / Python folder. First step is to add pySerial libray in the code:
import serial 
After that, we open a connection:
croduinoSerial = serial.Serial('COM71', 9600)
Keep in mind that 'COM71' and baud 9600 are specific for Windows computer that I use at this moment. More can be read on it pySerial API. Next step is making a loop which will continuously read data from serial port:
while True: #infinite loop
    if (croduinoSerial.inWaiting() > 0): #if any data exists
        myData = croduinoSerial.readline() #save files in myData
        print (myData)
The script can run with the F5 key. After that, in the Python Shell we can see print of data that Croduino/Arduino sent via serial port. If you have any further need to keep on processing received data, keep in mind that readline() stores variables as a string. You can change them in float by using:
myData_number = float(myData)

From Python on Croduino/Arduino

Sending data on Croduino/Arduino with Python 2.x is really simple:
import serial #if it hasn't been added already, add pySerial library

croduinoSerial = serial.Serial('COM71', 9600) 
croduinoSerial.write('text')

Python 3.x

In Python 3.x,  string is a unicode itself. If we want the library to work successfully, we must convert it in bytes, which wasn't necessary in Python 2.x
croduinoSerial.write(b'text')

What else?

There are several very good open-source platforms for realization of this communication. Most of them have a GUI (Graphical User Interface) framework for control, and some of them are running collected data in realtime in the form of diagram. Our recommendations are: Instrumentino Python Firmata GUI s pySerial i Matplotlib The plan in the upcoming lessons is for you to make something similar by yourself, so we can understand more easily the communication between Croduino/Arduino and Python. If you have difficulty performing that, feel free to leave a question or comment down below to improve this tutorial...