树莓派小车,从基础上手到完整工程(三)——设计html,网页操控,与小车交互

搭一个树莓派小车


网页操控

在自己设计的网页页面上添加几个按钮,进而操控小车。
在这里插入图片描述

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>

小注意

  1. html 文件放在 templates 文件夹中,文件夹要和 main.py 同目录
  2. host 设置为 0.0.0.0,代表外网访问(非本机访问),在外网上访问要使用本机的 ip,比如若树莓派的 ip 为1.1.1.1,默认端口为5000的话,则在浏览器中输入 1.1.1.1:5000
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值