Skip to content

Instantly share code, notes, and snippets.

@apendleton
Created October 30, 2014 14:45
Show Gist options
  • Save apendleton/7e5c1997cfa224f702e5 to your computer and use it in GitHub Desktop.
Save apendleton/7e5c1997cfa224f702e5 to your computer and use it in GitHub Desktop.
void setup() {
pinMode (2,OUTPUT);//attach pin 2 to vcc
pinMode (5,OUTPUT);//attach pin 5 to GND
// initialize serial communication:
Serial.begin(9600);
}
void loop()
{
digitalWrite(2, HIGH);
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;
// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(3, OUTPUT);// attach pin 3 to Trig
digitalWrite(3, LOW);
delayMicroseconds(2);
digitalWrite(3, HIGH);
delayMicroseconds(5);
digitalWrite(3, LOW);
// The same pin is used to read the signal from the PING))): a HIGH
// pulse whose duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode (4, INPUT);//attach pin 4 to Echo
duration = pulseIn(4, HIGH);
// convert the time into a distance
inches = microsecondsToInches(duration);
Serial.print(inches);
Serial.println();
delay(100);
}
long microsecondsToInches(long microseconds)
{
// According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
return microseconds / 74 / 2;
}
#!/usr/bin/python
import serial
import syslog
import time
import collections
# change to your Arduino serial device
port = '/dev/tty.usbmodemfa141'
distance = 0
def arduino_thread():
ard = serial.Serial(port,9600,timeout=5)
global distance
while True:
# Serial read section
msg = ard.readline().strip()
if msg:
distance = int(msg)
import threading
t = threading.Thread(target=arduino_thread, args=())
t.daemon = True
t.start()
# flask app
from flask import Flask, jsonify
from flask_cors import cross_origin
app = Flask(__name__)
@app.route('/')
@cross_origin()
def hello_world():
return jsonify({'distance': distance})
if __name__ == '__main__':
app.run()
Flask
Flask-Cors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment