This code help me to check and calculate distance between my sensor and object on his way.
import RPi.GPIO as GPIO
import time
import signal
import sys
# use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BCM)
# set GPIO Pins
pinTrigger = 23
pinEcho = 24
def close(signal, frame):
print("\nTurning off ultrasonic distance detection...\n")
GPIO.cleanup()
sys.exit(0)
signal.signal(signal.SIGINT, close)
# set GPIO input and output channels
GPIO.setup(pinTrigger, GPIO.OUT)
GPIO.setup(pinEcho, GPIO.IN)
while True:
# set Trigger to HIGH
GPIO.output(pinTrigger, True)
# set Trigger after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(pinTrigger, False)
startTime = time.time()
stopTime = time.time()
# save start time
while 0 == GPIO.input(pinEcho):
startTime = time.time()
# save time of arrival
while 1 == GPIO.input(pinEcho):
stopTime = time.time()
# time difference between start and arrival
TimeElapsed = stopTime - startTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2
print ("Distance: %.1f cm" % distance)
time.sleep(1)
Now i need to change/remake this code so that it will send my distance to plotly.
import plotly.plotly as py
from plotly.graph_objs import Scatter, Layout, Figure
import time
import readadc
username = 'a_user_name'
api_key = 'an_api_key'
stream_token = 'd0olq2nktv'
py.sign_in(username, api_key)
trace1 = Scatter(
x=,
y=,
stream=dict(
token=stream_token,
maxpoints=200
)
)
layout = Layout(
title='Raspberry Pi Streaming Sensor Data'
)
fig = Figure(data=[trace1], layout=layout)
print py.plot(fig, filename='Raspberry Pi Streaming Example Values')
# temperature sensor connected channel 0 of mcp3008
sensor_pin = 0
readadc.initialize()
i = 0
stream = py.Stream(stream_token)
stream.open()
#the main sensor reading loop
while True:
sensor_data = readadc.readadc(sensor_pin, readadc.PINS.SPICLK, readadc.PINS.SPIMOSI, readadc.PINS.SPIMISO, readadc.PINS.SPICS)
stream.write({'x': i, 'y': sensor_data})
i += 1
# delay between stream posts
time.sleep(0.25)