I'm trying to use the HC-SR04 ultrasonic sensor on a Raspberry Pi 3 with Python. I got the majority the code from this site. However, When I reduce the sleep time between each measurement of distance, The code gets stuck in the while GPIO.input(ECHO)==0: loop and then that stops everything. Maybe I'm setting the sleep time too low, But I really don't see how that would change anything.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
TRIG=23
ECHO=24
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
def pulseIn():
while True:
GPIO.output(TRIG, False)
time.sleep(.000005)
GPIO.output(TRIG, True) # Sending out a trigger pulse for 10 microseconds
time.sleep(.00001)
GPIO.output(TRIG, False)
pulse_start = time.time()
pulse_end = time.time()
while GPIO.input(ECHO)==0: # This is where it keeps getting stuck
pulse_start = time.time()
#if pulse_start-pulse_end>.5: # This is one of my attempts to fix the problem.
# It caused some bad output values
# continue
while GPIO.input(ECHO)==1:
pulse_end = time.time()
return pulse_end-pulse_start
time.sleep(2) # Giving the sensor some time to warm up
for i in range(100):
print(pulseIn()*17500)
time.sleep(.001) # It seems to work when I set this to 1, but I would prefer if it worked faster
Raspberry pi, unlike Arduino or other microcontroller platform, is a computer based on a Microprocessor and therefore has an operating system running on it to control software/hardware aspects of its operation. Multitasking Operating systems have schedulers that essentially provides all running processes, a chunk of hardware(cpu) to process instructions.
The caveat that comes with this is that, an instruction may not be executed immediately if the scheduler gives priority to other processes.
The following chunk of code would likely cause issues since getting the pulse is a time sensitive operation.
while GPIO.input(ECHO)==0:
pulse_start = time.time()
while GPIO.input(ECHO)==1:
pulse_end = time.time()
return pulse_end-pulse_start
Your loop would likely run infinitely if the sensor is done sending the low pulse and process start reading it then.
You could also get wildly incorrect values attributing to such delays.
So, what's the solution ?
If I were you, I would use a microcontroller to read the values from the sensor and then read the recorded data from it using I2c or any other communication protocol supported.
However you could also add a counter in your while loops to handle such cases like it is described here:
https://raspberrypi.stackexchange.com/questions/82833/hc-sr04-randomly-stops-taking-readings
From the datasheet we can see that this sensor has a maximum distance range of 4 meters. Hence, as you decrease the delay between two consecutive measurements, you might be sending another ultrasonic signal from the sensor when the previous signal has not arrived. Datasheet recommends 60 ms measurement cycle for this sensor. Your measurement cycle is much smaller than the recommended value.
Sensor datasheet:
https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf
This is a common problem with hc-src04. It stops working somehow. You should create another counter inside while loop. And then you should check that time to break inner while loop. Here is how I do it.
def distance(myStartingTime):
calculation_starting_time = time.time()
GPIO.output(trigger_pin,True)
time.sleep(0.00001)
GPIO.output(trigger_pin, False)
start = time.time()
end = time.time()
while GPIO.input(echo_pin) == 0:
calculation_starting_time = time.time()
if calculation_starting_time - myStartingTime > 1:
break
start = time.time()
while GPIO.input(echo_pin) == 1:
calculation_starting_time = time.time()
if calculation_starting_time - myStartingTime > 1:
break
end = time.time()
difference = end-start
distance = (difference*34300)/2
return distance
while True:
start = time.time()
my_distance = distance(start)
print("dist: ", my_distance)
Related
for measurement from my custom weather station I'm currently using two nested while loops to gather measuremet in 5seconds during 5min period as follows:
interval = 300
short_interval = 5
while True:
start_time = time.time()
while time.time() - start_time <= interval:
measurement_start = time.time()
reset_counter()
while time.time() - measurement_start <= short_interval:
store_directions.append(wind_direction.get_value())
final_speed = calculate_speed(wind_interval)
store_speeds.append(final_speed)
measure_rain()
do other stuff, mqtt etc.
which works fine - storing every 5seconds and sending everything out every 5mins
What I'm bit struggling is to accomodate another timeinterval of 60mins to gather rainfall.
Now it's measured every 5mins with measure_rain()
What would be best way how to keep 5min measurements for wind and another one for rainfall which will take 60min?
Another while? I was trying that, but ended up messing everything up ;)
Thank you for any help!
That's a task for concurrent programming. Luckily, Python has native support for it using Coroutines and Tasks. You can either roll your own based on the event loop and the example given there, or, look at what's out there already. Two quick picks:
asyncio-periodic looks minimal; less than 200 LoC class; seems to do one thing (execute periodic tasks every N seconds). Not actively developed (but why would it need to?)
schedule: much larger, but expressive syntax (schedule.every(10).minutes.do(job)) and looking well maintained. Bigger codebase, but advertised as having no further dependencies.
you can define each sensor as class and assign short and long intervals for each sensor. However this is CPU intensive work because of while loop without sleep.
import time
class wind:
big_interval=10
short_interval=2
st_bigInterval=time.time()
st_shortInterval=time.time()
class rain:
big_interval=10
short_interval=2
st_bigInterval=time.time()
st_shortInterval=time.time()
while True:
if(time.time()-wind.st_shortInterval>wind.short_interval):
print("collect wind data")
wind.st_shortInterval = time.time()
if(time.time()-rain.st_shortInterval>rain.short_interval):
print("collect rain data")
rain.st_shortInterval = time.time()
if(time.time()-wind.st_bigInterval>wind.big_interval):
print("send wind data")
wind.st_bigInterval = time.time()
wind.st_shortInterval = time.time()
if(time.time()-rain.st_bigInterval>rain.big_interval):
print("send rain data")
rain.st_bigInterval = time.time()
rain.st_shortInterval = time.time()
More better approach is to use timeloop as below.
import time
from timeloop import Timeloop
from datetime import timedelta
tl = Timeloop()
#tl.job(interval=timedelta(seconds=2))
def collectWindData():
print( "2s job current time : {}".format(time.ctime()), "collect wind data")
#tl.job(interval=timedelta(seconds=5))
def sendWindData():
print ("5s job current time : {}".format(time.ctime()), "send wind data")
#tl.job(interval=timedelta(seconds=2))
def collectRainData():
print( "2s job current time : {}".format(time.ctime()), "collect rain data")
#tl.job(interval=timedelta(seconds=5))
def sendRainData():
print ("5s job current time : {}".format(time.ctime()), "send rain data")
tl.start()
while True:
time.sleep(10)
a roll your own using the built in asyncio module. It's a strange new way of thinking about programming and can be quite challenge to get your head around. Below is a niave implementation if you don't need to be precise on when you measured. You can make a precise version using a priority queue to put the next measurement first. A common approach to this problem is used in collision mechanics for games programming.
import asyncio
import random
async def measure_rain():
while True:
print(f'rainfall {random.randint(0,100)}') #measure rainfall
await asyncio.sleep(1)
return True
async def measure_wind():
while True:
print(f'windspeed: {float(random.randint(0, 100)/10)} m/s') #measure windspeed
await asyncio.sleep(3)
return True
async def main():
tasks = []
tasks.append(asyncio.create_task(measure_rain()))
tasks.append(asyncio.create_task(measure_wind()))
await *tasks
asyncio.run(main())
I am trying to make a python script that works in a loop mode with iteration through a text file to run for periods of one hour and make 30minute pauses between each hour loop .
After some searching I found this piece of code :
import datetime
import time
delta_hour = 0
while:
now_hour = datetime.datetime.now().hour
if delta_hour != now_hour:
# run your code
delta_hour = now_hour
time.sleep(1800) # 1800 seconds sleep
# add some way to exit the infinite loop
This code has a few issues though :
It does not consider one hour periods since the script starts running
It does not seem to work continuously for periods over one hour
Considering what I am trying to achieve (running script 1hour before each time it pauses for 30mins) what is the best approach to this ? Cron is not an option here .
For clarification :
1hour run -- 30min pause -- repeat
Thanks
Here is a so simple code, I have written for teaching purposes, which is very clear
from datetime import datetime
class control_process():
def __init__(self, woking_period, sleeping_period):
self.woking_period = woking_period # working period in minutes
self.sleeping_period = sleeping_period # sleeping period in minutes
self.reset()
def reset(self):
self.start_time = datetime.utcnow() # set starting point
def manage(self):
m = (datetime.utcnow() - self.start_time).seconds / 60 # how long since starting point
if m >= self.woking_period: # if exceeded the working period
time.sleep(self.sleeping_period * 60) # time to sleep in seconds
self.reset() # then reset time again
return # go to continue working
cp = control_process(60, 30) # release for 60 minutes and sleep for 30 minutes
while True: # you code loop
cp.manage()
'''
your code
'''
in which 'control_processobject - I calledcp- callscp.manage()` inside your executing loop.
you reset time via cp.reset() before going in the loop or whenever you want
Based on Comments
The simplicity I mean is to add this class to your general library so you can use it whenever you want by instantiation of cp then one or two controlling functions 'cp.manage()` which control the working cycles, and cp.reset() if you want to use it in another location of the code. I believe that use a function is better than a long condition statement.
Using the default library you could do something like call the script itself using subprocess. By checking whether conditions are met the process could do a task and call itself. Extending the logic with a kill pill would make it stop (I leave that up to you).
import argparse, time
from subprocess import call
DELAY = 60 * 30 # minutes
WORK_TIME = 60 * 60 # minutes
parser = argparse.ArgumentParser()
parser.add_argument("-s",
help = "interval start time",
type = float,
default = time.time())
parser.add_argument("-t",
help = "interval stop time",
type = float,
default = time.time() + WORK_TIME)
def do_task():
# implement task
print("working..")
return
if __name__ == "__main__":
args = parser.parse_args()
start = args.s
stop = args.t
# work
if start < time.time() < stop:
do_task()
# shift target
else:
start = time.time() + DELAY
stop = start + WORK_TIME
call(f"python test.py -t {stop} -s {start}".split())
The simplest solution I could come up with was the following piece of code, which I added inside my main thread :
start_time = int(time())
... #main thread code
#main thread code end
if int(time() - start_time >= 60 * 60):
print("pausing time")
sleep(30 * 60)
start_time = int(time())
From the moment the script starts this will pause every hour for 30mins and resume afterwards .
Simple yet effective !
I need to read a temperature reading from a DS18B20 sensor using Raspberry Pi 3 and Python.
The problem is the refresh rate of the sensor (~1 sec)
I need to read from sys/bus/w1/devices/28-041670f43bff/w1_slave and use the integer i get to display a temperature on a 7 segment display connected directly to my GPIOs (not using any hardware multiplexing - i2c....etc)
In order to display a two digit temperature, I need to turn on and off the digits really fast (faster than the sensor refreshes)
This is the small piece of code used to get the integer temperature:
def temperature():
with open ("/sys/bus/w1/devices/28-041670f43bff/w1_slave") as q:
r=q.read()
temp=r[69:71]
t=int (temp)
return t
But i need to call this function many times per second in order to get a good display on the 7 segment display.
This is how i thought of doing it:
#the temperature() function returns a two digit int
while True:
GPIO.output(31,0)
GPIO.output(temp[temperature()/10], 1) # temp is a dictionary used to know which segments to light up to show numbers
time.sleep(0.0005)
GPIO.output(31,1)
GPIO.output(37,0)
GPIO.output(temp[temperature()%10], 1)
time.sleep(0.0005)
GPIO.output(37,1)
But this code just makes one digit light up, wait ~1sec, light up the other digit, wait ~1sec.....and so on.
Any ideas of how to do this are very appreciated.
Rather than implement this functionality on your own, you should instead use the libraries out there that address this particular bit of your code inherently. In this case, I'd suggest you use W1ThermSensor. You can find the documentation at:
https://github.com/timofurrer/w1thermsensor
and you can install it using:
pip install w1thermsensor
It does support the DS18B20, and offers an exact analogue to your use case in the README.
From the docs for the package:
from w1thermsensor import W1ThermSensor
sensor = W1ThermSensor()
temperature_in_celsius = sensor.get_temperature()
temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F)
temperature_in_all_units = sensor.get_temperatures([
W1ThermSensor.DEGREES_C,
W1ThermSensor.DEGREES_F,
W1ThermSensor.KELVIN
])
In many cases, particularly for popular hardware devices, you'll find that there are libraries already available to use within python, and that will all you to quickly move on to writing the bits of code unique to your own particular needs.
Note: According to the technical discussion in the following link, if the DS18B20 is set to 12-bit temperature resolution, the temperature conversion will take 750 ms, or 3/4 of a second. If you set the hardware to do 9-bit resolution, the conversion time in hardware is 93.75 ms. I suspect this is the root of your once-per-second issue.
https://www.maximintegrated.com/en/app-notes/index.mvp/id/4377
There is some discussion of this issue in this Question:
https://raspberrypi.stackexchange.com/questions/14278/how-to-change-ds18b20-reading-resolution
See the second Answer, regarding the configDS18B20 utility.
With the resolution set to 9-bit, you may be able to adjust the w1thermsensor RETRY_DELAY_SECONDS / RETRY_ATTEMPTS value combination in the source code and get what you need. It's unclear to me if the retry delay has any affect on the actual polling of the device. It looks like it is there for device finding. Though, as I said, that interval may impact polling a single device. I simply didn't read through the source code enough to see when and where it comes into play.
Happy New Year!
I'd throw the display routine into its own thread so that you don't have to think about it in your main loop. The code below should demonstrate this concept. Set "testing" to False to see if it works with your hardware.
#!/usr/bin/python
import time
import threading
import Queue
import random
# Set this to False to read the temperature from a real sensor and display it on a 7-digit display.
testing = True
def temperature_read(q):
# Read the temperature at one second intervals.
while True:
if testing:
r = '-' * 69 + '%02d' % (random.randrange(100)) + 'blahblah' * 4
else:
r = open('/sys/bus/w1/devices/28-041670f43bff/w1_slave', 'r').read()
print r
# The temperature is represented as two digits in a long string.
# Push the digits into the queue as a tuple of integers (one per digit).
q.put((int(r[69]), int(r[70])))
# Wait for next reading.
# (Will w1_slave block until the next reading? If so, this could be eliminated.)
time.sleep(1.0)
def temperature_display(q):
# Display the temperature.
# Temperature is two digits, stored separately (high/low) for more efficient handling.
temperature_h = temperature_l = 0
while True:
# Is there a new temperature reading waiting for us?
if not q.empty():
temperature = q.get()
# If it's None, we're done.
if temperature is None:
break
# Load the two digits (high and low) representing the temperature.
(temperature_h, temperature_l) = temperature
if testing:
print 'displayH', temperature_h
time.sleep(0.05)
print 'displayL', temperature_l
time.sleep(0.05)
else:
GPIO.output(31,0)
GPIO.output(temperature_h, 1) # temp is a dictionary used to know which segments to light up to show numbers
time.sleep(0.0005)
GPIO.output(31,1)
GPIO.output(37,0)
GPIO.output(temperature_l, 1)
time.sleep(0.0005)
GPIO.output(37,1)
# Clean up here. Turn off all pins?
# Make a queue to communicate with the display thread.
temperature_queue = Queue.Queue()
# Run the display in a separate thread.
temperature_display_thread = threading.Thread(target=temperature_display, args=(temperature_queue,))
temperature_display_thread.start()
# Run the reader.
try:
temperature_read(temperature_queue)
except:
# An uncaught exception happened. (It could be a keyboard interrupt.)
None
# Tell the display thread to stop.
temperature_queue.put(None)
# Wait for the thread to end.
temperature_display_thread.join()
To support another reading (transmission), I just put it in the read loop rather than adding another thread for it. I changed the queue so that you could easily move it to another thread but I suspect you'll add more inputs so this is probably a reasonable way to do it unless the read frequency of one needs to be much different. (Even then, you could do things with counters in the loop.)
#!/usr/bin/python
import time
import threading
import Queue
import random
# Set this to False to read the temperature from a real sensor and display it on a 7-digit display.
testing = True
def observe(q):
while True:
# Make a temperature reading.
if testing:
r = '-' * 69 + '%02d' % (random.randrange(100)) + 'blahblah' * 4
else:
r = open('/sys/bus/w1/devices/28-041670f43bff/w1_slave', 'r').read()
print 'temperature ->', r
# The temperature is represented as two digits in a long string.
# Push the digits into the queue as a tuple of integers (one per digit).
q.put(('temperature', int(r[69]), int(r[70])))
# Make a transmission reading.
if testing:
r = random.randrange(1,6)
else:
r = 0 # Put your transmission reading code here.
print 'transmission ->', r
q.put(('transmission', r))
# Wait for next reading.
# (Will w1_slave block until the next reading? If so, this could be eliminated.)
time.sleep(1.0)
def display(q):
# Display the temperature.
# Temperature is two digits, stored separately (high/low) for more efficient handling.
temperature_h = temperature_l = transmission = 0
while True:
# Is there a new temperature reading waiting for us?
if not q.empty():
reading = q.get()
# If it's None, we're done.
if reading is None:
break
elif reading[0] == 'temperature':
# Load the two digits (high and low) representing the temperature.
(x, temperature_h, temperature_l) = reading
elif reading[0] == 'transmission':
(x, transmission) = reading
if testing:
print 'displayH', temperature_h
time.sleep(0.05)
print 'displayL', temperature_l
time.sleep(0.05)
print 'transmission', transmission
time.sleep(0.05)
else:
GPIO.output(31,0)
GPIO.output(temperature_h, 1) # temp is a dictionary used to know which segments to light up to show numbers
time.sleep(0.0005)
GPIO.output(31,1)
GPIO.output(37,0)
GPIO.output(temperature_l, 1)
time.sleep(0.0005)
GPIO.output(37,1)
# Clean up here. Turn off all pins?
# Make a queue to communicate with the display thread.
readings_queue = Queue.Queue()
# Run the display in a separate thread.
display_thread = threading.Thread(target=display, args=(readings_queue,))
display_thread.start()
# Observe the inputs.
try:
observe(readings_queue)
except:
# An uncaught exception happened. (It could be a keyboard interrupt.)
None
# Tell the display thread to stop.
readings_queue.put(None)
# Wait for the thread to end.
display_thread.join()
Here's a version which only reads the temperature every tenth time but reads the transmission every time. I think you'll see how to easily tweak this to meet your needs.
I would make separate threads for each reader but it would complicate the thread management quite a bit.
#!/usr/bin/python
import time
import threading
import Queue
import random
# Set this to False to read the temperature from a real sensor and display it on a 7-digit display.
testing = True
def observe(q):
count = 0
while True:
# Only read the temperature every tenth time.
if (count % 10 == 0):
# Make a temperature reading.
if testing:
r = '-' * 69 + '%02d' % (random.randrange(100)) + 'blahblah' * 4
else:
r = open('/sys/bus/w1/devices/28-041670f43bff/w1_slave', 'r').read()
print 'temperature ->', r
# The temperature is represented as two digits in a long string.
# Push the digits into the queue as a tuple of integers (one per digit).
q.put(('temperature', int(r[69]), int(r[70])))
# Make a transmission reading.
if testing:
r = random.randrange(1,6)
else:
r = 0 # Put your transmission reading code here.
print 'transmission ->', r
q.put(('transmission', r))
# Wait for next reading.
if testing:
time.sleep(0.5)
else:
time.sleep(0.1)
count += 1
def display(q):
# Display the temperature.
# Temperature is two digits, stored separately (high/low) for more efficient handling.
temperature_h = temperature_l = transmission = 0
while True:
# Is there a new temperature reading waiting for us?
if not q.empty():
reading = q.get()
# If it's None, we're done.
if reading is None:
break
elif reading[0] == 'temperature':
# Load the two digits (high and low) representing the temperature.
(x, temperature_h, temperature_l) = reading
elif reading[0] == 'transmission':
(x, transmission) = reading
if testing:
print 'displayH', temperature_h
time.sleep(0.05)
print 'displayL', temperature_l
time.sleep(0.05)
print 'transmission', transmission
time.sleep(0.05)
else:
GPIO.output(31,0)
GPIO.output(temperature_h, 1) # temp is a dictionary used to know which segments to light up to show numbers
time.sleep(0.0005)
GPIO.output(31,1)
GPIO.output(37,0)
GPIO.output(temperature_l, 1)
time.sleep(0.0005)
GPIO.output(37,1)
# Clean up here. Turn off all pins?
# Make a queue to communicate with the display thread.
readings_queue = Queue.Queue()
# Run the display in a separate thread.
display_thread = threading.Thread(target=display, args=(readings_queue,))
display_thread.start()
# Observe the inputs.
try:
observe(readings_queue)
except:
# An uncaught exception happened. (It could be a keyboard interrupt.)
None
# Tell the display thread to stop.
readings_queue.put(None)
# Wait for the thread to end.
display_thread.join()
I'm reading serial data with a while loop. However, I have no control over the sample rate.
The code itself seems to take 0.2s to run, so I know I won't be able to go any faster than that. But I would like to be able to control precisely how much slower I sample.
I feel like I could do it using 'sleep', but the problem is that there is potential that at different points the loop itself will take longer to read(depending on precisely what is being transmitted over serial data), so the code would have to make up the balance.
For example, let's say I want to sample every 1s, and the loop takes anywhere from 0.2s to 0.3s to run. My code needs to be smart enough to sleep for 0.8s (if the loop takes 0.2s) or 0.7s (if the loop takes 0.3s).
import serial
import csv
import time
#open serial stream
while True:
#read and print a line
sample_value=ser.readline()
sample_time=time.time()-zero
sample_line=str(sample_time)+','+str(sample_value)
outfile.write(sample_line)
print 'time: ',sample_time,', value: ',sample_value
Just measure the time running your code takes every iteration of the loop, and sleep accordingly:
import time
while True:
now = time.time() # get the time
do_something() # do your stuff
elapsed = time.time() - now # how long was it running?
time.sleep(1.-elapsed) # sleep accordingly so the full iteration takes 1 second
Of course not 100% perfect (maybe off one millisecond or another from time to time), but I guess it's good enough.
Another nice approach is using twisted's LoopingCall:
from twisted.internet import task
from twisted.internet import reactor
def do_something():
pass # do your work here
task.LoopingCall(do_something).start(1.0)
reactor.run()
An rather elegant method is you're working on UNIX : use the signal library
The code :
import signal
def _handle_timeout():
print "timeout hit" # Do nothing here
def second(count):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(1)
try:
count += 1 # put your function here
signal.pause()
finally:
signal.alarm(0)
return count
if __name__ == '__main__':
count = 0
count = second(count)
count = second(count)
count = second(count)
count = second(count)
count = second(count)
print count
And the timing :
georgesl#cleese:~/Bureau$ time python timer.py
5
real 0m5.081s
user 0m0.068s
sys 0m0.004s
Two caveats though : it only works on *nix, and it is not multithread-safe.
At the beginning of the loop check if the appropriate amount of time has passed. If it has not, sleep.
# Set up initial conditions for sample_time outside the loop
sample_period = ???
next_min_time = 0
while True:
sample_time = time.time() - zero
if sample_time < next_min_time:
time.sleep(next_min_time - sample_time)
continue
# read and print a line
sample_value = ser.readline()
sample_line = str(sample_time)+','+str(sample_value)
outfile.write(sample_line)
print 'time: {}, value: {}'.format(sample_time, sample_value)
next_min_time = sample_time + sample_period
I am debugging my code for which I need to write a python script that can read data being sent over the serial port through bluetooth and calculate the time elapsed between each successive packet.I know how to read the data from the serial port but I am having issues with calculating the time between each packet.
Any suggestions would be very helpful.
Thanks!
Something like this might do the trick. Just create a IntTimer() object and call .stamp() on it whenever you receive a packet. It's just a start, so if it does what you want then you might need to change it to clean up the old stamps etc., otherwise self.timestamps will just grow and grow. You could use self.timestamps to work out average times etc. between packets.
import time
class IntTimer:
def __init__(self):
self.timestamps = []
def stamp(self):
if self.timestamps:
last = self.timestamps[-1]
else:
last = False
now = time.time()
self.timestamps.append(now)
if last:
#return the time since the last packet
return now - last
else:
return -1
This is quite a simple answer, so if you're asking a more complicated question then do say so.
Why don't you use python time module to calculate time diff? If you need beter precision you can implement your own timer using the select system call.
But a better solution is to use something like Portmon
I would use time.time() and subtract to find the number of seconds elapsed.
import time
# receive one packet
t0 = time.time()
# then receive the other packet
t1 = time.time()
print 'Time between packets (seconds):', t1 - t0
So this is what I wrote and it worked.Thank you all for your answers.
#!/bin/python
import serial
import time
time_stamp_prev = 0
ser = serial.Serial( \
port="/dev/tty.bluetoothmodule", \
baudrate=115200, \
parity=serial.PARITY_NONE, \
stopbits=serial.STOPBITS_ONE, \
bytesize=serial.EIGHTBITS )
while True:
if ser.inWaiting() > 0:
print ser.readline();
time_stamp_curr = time.time()
time_between_packets = time_stamp_curr - time_stamp_prev
time_stamp_prev = time_stamp_curr