这篇文章主要介绍了python3怎么实现网页版树莓派小车控制,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

Python是一种跨平台的、具有解释性、编译性、互动性和面向对象的脚本语言,其最初的设计是用于编写自动化脚本,随着版本的不断更新和新功能的添加,常用于用于开发独立的项目和大型项目。
如何实现通过网页实现小车控制的。当前的实现方式比较简陋,只能支持控制网页和树莓派在同一个局域网中的场景。如果以后还有精力,可能会进行一些改进。
1. 基本思路

2. 服务端控制程序server.py
# --coding:utf-8--
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
import socket
import urllib
from car_controler import FourWheelDriveCar
from camera_controler import Camera
class CarServer(BaseHTTPRequestHandler):
carControler = FourWheelDriveCar()
cameraControler = Camera()
def get_host_ip(self):
'''
This method is used for getting local ip address
The car server will deploy on this ip
'''
try:
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverSocket.connect(("8.8.8.8", 80))
localIP = serverSocket.getsockname()[0]
finally:
return localIP
def do_GET(self):
'''
Define the car control GUI for client
For the first edition, it will only return direction contol GUI
'''
localIP = CarServer.get_host_ip(self)
# When this GET method is called, then should init the car
self.carControler.reset()
# Read control page html file from control.html
controlPageFile = open("control.html")
controlPageGUI = controlPageFile.read()
controlPageFile.close()
controlPageGUI = controlPageGUI.replace(
"requestAddress", "http://" + localIP + ":9090/")
controlPageGUI = controlPageGUI.replace(
"cameraAddress", "http://" + localIP + ":8080/")
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(controlPageGUI.encode())
def do_POST(self):
length = int(self.headers['Content-Length'])
qs = self.rfile.read(length)
direction = qs.decode()
print(direction)
cameraDirection = ['HR', 'HL', 'VU', 'VD', 'RESET']
if direction in cameraDirection:
# This is used to control the camera
self.cameraControler.cameraRotate(direction)
else:
# This is used to control the car
self.carControler.carMove(direction)
self.send_response(200)
if __name__ == "__main__":
raspCarServer = CarServer
hostIP = raspCarServer.get_host_ip(raspCarServer)
hostPort = 9090
myServer = HTTPServer((hostIP, hostPort), raspCarServer)
print(time.asctime(), "Server Starts - %s:%s" % (hostIP, hostPort))
try:
myServer.serve_forever()
except KeyboardInterrupt:
pass3. 服务端返回的页面control.html
几点说明:
html文件中有两个地址,我是在server.py中做了替换的,所以client请求之后会有实际的地址给到浏览器,最终都是使用的树莓派的ip
有个显示监控视频的区域,可以直接用我给出的示例使用即可,前提是你也用的MJPG-Streamer来获取摄像头监控
小车控制我只给来前后左右运动,没有给后退的转向控制,有需要可以自己添加
比较重要的是点击按钮之后发送请求到服务端,参考文件