Raspberry Pi超声波测距仪与WebIOPi

时间:2015-07-12 12:37:20

标签: raspberry-pi webiopi

我正在开展一个项目,用Raspberry Pi控制一辆遥控车,并在WeiOPi的帮助下完成。

现在我想在其上添加超声波测距仪(我有HC-SR04)。 我在互联网上搜索了它并没有找到太多信息,我有一个问题。 我如何将python代码与java-script和html结合起来打印网页上的距离。

提前致谢, 任何帮助将不胜感激。

此致 H.M

P.S,我只有13岁,是编程新手。

修改

未完成的代码:

python代码是:

import webiopi
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)

TRIG = 23
ECHO = 24

print "Distance Measurement In Progress"

GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)

GPIO.output(TRIG, False)
print "Waiting For Sensor To Settle"
time.sleep(2)

GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)

while GPIO.input(ECHO)==0:
  pulse_start = time.time()

while GPIO.input(ECHO)==1:
  pulse_end = time.time()

pulse_duration = pulse_end - pulse_start

distance = pulse_duration * 17150
# _____________________________________________________________________
# I want to print the following string (distance) to print on html page
# ---------------------------------------------------------------------
@webiopi.macro
def getSensor(channel):
    percent = round(distance, 2)
    return "%.2f%%" % percent

#Instantiate the server on the port 8000, it starts immediately in its own thread
server = webiopi.Server(port=8000)

# Run our loop until CTRL-C is pressed or SIGTERM received
webiopi.runLoop()

# -------------------------------------------------- #
# Termination part                                   #
# -------------------------------------------------- #

# Stop the server
server.stop()

HTML代码:

    <script type="text/javascript" src="/webiopi.js"></script>
    <script type="text/javascript">
        webiopi().ready(init);

        // defines function passed previously to webiopi().ready()
        function init() {
                // automatically refresh UI each seconds
                setInterval(updateUI, 1000);
        }

        // function called through setInterval
        function updateUI() {
                webiopi().callMacro("getSensor", 0, sensorCallback);
                webiopi().callMacro("getSensor", 1, sensorCallback);
                webiopi().callMacro("getSensor", 2, sensorCallback);
                webiopi().callMacro("getSensor", 3, sensorCallback);
        }       

        // callback function used to display sensor data
        function sensorCallback(macroName, channel, data) {
                // use jQuery to change spans content
                $("#sensor"+channel).text(data);
        }

    </script>
</head>
<body>
    <div align="center">
        <div>Sensor 0: <span id="sensor0"></span></div>
        <div>Sensor 1: <span id="sensor1"></span></div>
        <div>Sensor 2: <span id="sensor2"></span></div>
        <div>Sensor 3: <span id="sensor3"></span></div>
    </div>
</body>
</html>

0 个答案:

没有答案