网页操控
在自己设计的网页页面上添加几个按钮,进而操控小车。
main.py
from flask import Flask, render_template, Response
from motor import Motor
motor = Motor()
app = Flask(__name__)
@app.route('/')
def template():
return render_template('index.html') # 返回事先完成的html文档,使其显示在网页上
@app.route("/front")
def front():
motor.Front()
print("front")
return ""
@app.route("/left")
def left():
motor.Left()
print("left")
return ""
@app.route("/right")
def right():
motor.Right()
print("right")
return ""
@app.route("/rear")
def rear():
motor.Rear()
print("rear")
return ""
app.run(host="0.0.0.0")
html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>小外甥的酷炫小车</title>
<meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible">
<style>
body {
text-align: center;
background-color: white;
}
button {
width: 100px;
height: 100px;
font-size: 50px;
color: white;
padding: 10px 20px;
background-color: black;
font-weight: 1500;
cursor: pointer;
border-radius: 30px;
}
#front {
position: absolute;
top: 100px;
left: 180px;
}
#left{
position: absolute;
top: 220px;
left: 60px;
}
#right{
position: absolute;
top: 220px;
left: 300px;
}
#rear{
position: absolute;
top: 340px;
left: 180px;
}
</style>
<script>
function move(self)
{
var xmlthhp;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",self.id,true);
xmlhttp.send();
}
</script>
</head>
<body>
<button id="front" onclick="move(this)">↑</button>
<button id="left" onclick="move(this)">←</button>
<button id="right" onclick="move(this)">→</button>
<button id="rear" onclick="move(this)">↓</button>
</body>
</html>
小注意
- html 文件放在 templates 文件夹中,文件夹要和 main.py 同目录
- host 设置为 0.0.0.0,代表外网访问(非本机访问),在外网上访问要使用本机的 ip,比如若树莓派的 ip 为1.1.1.1,默认端口为5000的话,则在浏览器中输入 1.1.1.1:5000