import serial                               # Import serial library
import matplotlib.pyplot as plt     
import numpy as np                      
from drawnow import*

dur = [ ]                                       # Definition of the variables
dist = [ ]

arduinoData = serial.Serial('/dev/cu.usbserial-A9071I4P', 9600) # Here is the serial USB port name and the baud rate from Arduino IDE
plt.ion( )

def MakeFig( ):
    plt.plot (dur, 'b*', label='Duration')
    plt.legend(loc='upper left')
    plt.title ('Distance Measurement using Ultrasonic Sensor HC-SR04 and ATmega328p-PU')
    plt.xlabel('readings')
    plt.ylabel('Duration [miliseconds]')
    plt2=plt.twinx( )                                           # Add secon Y Axis        
    plt2.plot (dist, 'ro', label='Distance')
    plt2.legend(loc='upper right')                      # Legend Position
    plt2.ylabel('Distance [cm]')
    
 
while (True):
    while (arduinoData.inWaiting ( ) == 0):  # while there is no data, 
            pass                                                # do nothing
    arduino = arduinoData.readline( ) # ... than read waiting data to the variable arduino
    dataArray = arduino.split()          # split data into array with two elements
    duration = float(dataArray[0])   #convert first reading data of the array from "string" to a "float" format
    distance = int(dataArray[1])     #convert second reading data of the array from "string" to a "float" format
    dur.append(duration)             #collect any further reading data of the variable "duration" into array "dur"
    dist.append(distance)            #collect any further reading data of the variable "duration" into array "dist"
    
    drawnow(MakeFig)             # use the command "drawnow" from the package tool to plot the function "MakeFig"
    plt.pause(0.000001)          # make a very small pause to ....




