I'm working on a little project using the MaxSonar EZ1 ultrasonic range sensor and Arduino Diecimila.
Using the MaxSonar playground code, I have Arduino writing the number of inches to serial every .5 seconds, along with a delimiter. When monitoring the serial data, the output looks similar to:
5.13.15.12.123.39.345...
On the Python side, I have a basic Flask app with a /distance route that returns a JSON object with the serial value:
from flask import Flask
from flask import render_template
import serial
import json
import random
app = Flask(__name__,
static_folder="public",
template_folder="templates")
port = "/dev/tty.usbserial-A6004amR"
ser = serial.Serial(port,9600)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/distance")
def distance():
distance = read_distance_from_serial()
return json.dumps({'distance': distance})
def read_distance_from_serial():
x = ser.read();
a = '';
while x is not '.':
a += x;
x = ser.read()
print(a)
return a
# return random.randint(1, 100)
if __name__ == "__main__":
app.debug = True
app.run()
And index.html is a basic site with some JS that polls /distance every half second for a new reading. With the value, I should be able to build an interesting UI that changes based on how close/far I am from the sonar.
$(document).ready(function() {
window.GO = function() {
this.frequency = 500; // .5 seconds
this.init = function() {
window.setInterval(this.update_distance, 500);
}
this.update_distance = function() {
$.get('/distance', function(response) {
var d = response.distance;
$('#container').animate({"width": d + "%"});
}, 'json')
}
}
go = new GO();
go.init();
});
The Question
The issue I'm running into is that there is no guarantee that when python reads from serial, that there will be a value. Often times, when it polls, I get either an empty value or a partial value, while other times it is spot on.
How can I change my technique such that I am able to consistently poll the serial data and receive the last good reading from the Arduino serial output?