Video Control Car Based on Flask Framework

by chimicron in Circuits > Remote Control

442 Views, 4 Favorites, 0 Comments

Video Control Car Based on Flask Framework

1.jpg

Re-engraving is inheritance, transcendence is innovation, and integration is the constant collision between inheritance and innovation, and it is from this constant collision that many classics are derived. Everyone is constantly creating and innovating in their respective industries, and makers are found in art, music, architecture, science, entertainment, and more. In recent years, more and more people have realized the importance of cross-border integration. Only those who combine the strengths of many families and integrate wisdom from multiple fields can create more classics.

1. Project Selection

2.jpg

Many years ago, I used the open source robot teaching materials of Teacher Xie to try the sports car for the first time. The main control board is the Romeo V1 controller + MiniQ robot chassis, and now it has been iterated to the V2 version; modular programming and line inspection were the most popular cases at that time.

The new curriculum standard requires high school information technology to introduce Python language and Internet of Things technology. How to combine open source hardware and Internet of Things preparation cases on the basis of speaking the language has become our common task. This round of challenge project is " Video Control Car Based on Flask Framework" The collision of new technologies + new ideas will surely bring infinite possibilities. In order to write this case, I read through the library's html and css web design textbooks, and learned the basic course of flask framework; However, my ability is limited, and I welcome all colleagues to criticize and correct me and improve it together. The specific implementation function is shown in the following figure

2. Knowledge Reserve

1. What is Flask? (Raspberry Pi builds flask framework server)

Flask is a web micro-framework implemented by python that allows us to quickly implement a website or web service using the Python language. More flexible, lightweight, secure and easy to use than other similar frameworks. It can be well developed in combination with the MVC pattern, and the developers can divide and cooperate, and a small team can complete the realization of small and medium-sized websites or Web services with rich functions in a short period of time. In addition, Flask also has strong customization, users can add corresponding functions according to their own needs, and realize the enrichment and expansion of functions while keeping the core functions simple. Its powerful plug-in library allows users to realize personalized websites Customize and develop a powerful website. Installation command pip install flask Flask small case Create a new py file and enter 7 sample codes from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run() Run the code, log in to 127.0.0.1:5000, you can see the web page showing Hello World!

2. What is streaming? (Data format for car video viewing) Streaming media refers to a technology and process that compresses a series of media data, sends data in segments through the Internet, and transmits video and audio on the Internet for viewing in real time. This technology enables data packets to be sent like flowing water; if Without this technique, the entire media file would have to be downloaded before use. Streaming transmission can transmit live audio and video or pre-stored video on the server. When the viewer is watching these audio and video files, the audio and video data will be played by specific playback software immediately after being delivered to the viewer's computer. 3. How to output video stream to browser? (How to get video) Opencv uses the flask framework to build a real-time video stream server by obtaining the local real-time video stream, and then other machines can obtain the real-time video stream on this machine by sending requests to this server. Common network cameras use this method to transmit video. 4. HTML (Hypertext Markup Language) (writing the front-end car control interface) HyperText Markup Language (English: HyperText Markup Language, referred to as: HTML) is a standard markup language used to create web pages. You can use HTML to build your own WEB site. HTML runs on the browser and is parsed by the browser. 5. CSS (Cascading Style Sheets) (This part is an improvement article and is a common technique for optimizing homepages) Cascading Style Sheets (English full name: Cascading Style Sheets) is a computer language used to represent document styles such as HTML (an application of the Standard Universal Markup Language) or XML (a subset of the Standard Universal Markup Language). CSS can not only modify web pages statically, but also dynamically format various elements of web pages with various scripting languages. CSS can perform pixel-level precise control over the layout of element positions in web pages, supports almost all font size styles, and has the ability to edit web page objects and model styles. 6.GPIO (Raspberry Pi sends commands to the L298N motor driver board through GPIO to control the movement of the car) GPIO (English: General-purpose input/output), short for general-purpose input and output; its pins can be freely used by users by program control, and the PIN pin can be used as general-purpose input (GPI) or general-purpose output (GPO) according to practical considerations or General Purpose Input and Output (GPIO). 7. L298N drive module (drive 2 motors) L298N, a motor driver that accepts high voltage, can drive both DC motors and stepper motors. A driver chip can control two DC gear motors to do different actions at the same time, in the voltage range of 6V to 46V, providing a current of 2 amps, and has the functions of overheating and self-cutting and feedback detection. The laboratory is standard, the price is cheap, and the data is flying everywhere.

Bill of Materials

3.jpg

Bill of MaterialsBill of Materials

1x Raspberry Pi 4B

1x Camera

1x L298N Motor Driver Module

1x A set of metal crawler trolley (including 2 18650 batteries)

1x 1 power bank (raspberry pie power supply)

5 x Dupont wire (one female to male, four female to female)

Recommended: Chimicron Electronic Devices Mall can buy the items needed for this project

Assembly Trolley

4.png
5.png
7.jpg
6.jpg
8.jpg

The frame can be assembled according to the instructions, or can be replaced with similar styles. The assembly steps are omitted.

Car connection diagram
Note: Raspberry Pi is powered by a power bank, please pay attention

Focus: trolley motor, L298N, Raspberry Pi and line connection
1. The left and right blue lines are connected to the motor M1 and M2 respectively.

2. The positive pole of the 18650 battery box is connected to 12V power supply, and the negative pole is connected to GND. The mobile power supply supplies power to the Raspberry Pi through USB Type-C. Note that the Raspberry Pi needs to share the ground with the battery box. The GND pin of the Raspberry Pi should be shared with the negative pole of the battery box

3. The blue connection IN1 is connected to the Raspberry Pi 11 pin
Green connection IN2 connects to Raspberry Pi 13 pins The yellow connection IN1 is connected to the Raspberry Pi 15 pin Red connection IN1 connects to Raspberry Pi 16 pins Pay attention to the black connection pin 6; the Raspberry Pi GND and the battery pack share the same ground

4. Channel A enable and channel B enable can be disconnected, so that the car can move but cannot adjust the speed.

The Car Moves

9.jpg

The principle of trolley movement

The programming software is Tonny editor, python3.7

codecode

#导入GPIO库
import RPi.GPIO as GPIO import time #设置GPIO模式 GPIO.setmode(GPIO.BOARD) #设置in1到in4接口 IN1 = 11 IN2 = 13 IN3 = 15 IN4 = 16 #初始化接口 # def init(): # GPIO.setup(IN1,GPIO.OUT) # GPIO.setup(IN2,GPIO.OUT) # GPIO.setup(IN3,GPIO.OUT) # GPIO.setup(IN4,GPIO.OUT) GPIO.setup(IN1,GPIO.OUT) GPIO.setup(IN2,GPIO.OUT) GPIO.setup(IN3,GPIO.OUT) GPIO.setup(IN4,GPIO.OUT) #小车前进函数函数 def front(): GPIO.output(IN1,GPIO.HIGH) GPIO.output(IN2,GPIO.LOW) GPIO.output(IN3,GPIO.HIGH) GPIO.output(IN4,GPIO.LOW) #小车后退函数 def back(): GPIO.output(IN1,GPIO.LOW) GPIO.output(IN2,GPIO.HIGH) GPIO.output(IN3,GPIO.LOW) GPIO.output(IN4,GPIO.HIGH) #小车左转函数 def left(): GPIO.output(IN1,GPIO.LOW) GPIO.output(IN2,GPIO.LOW) GPIO.output(IN3,GPIO.HIGH) GPIO.output(IN4,GPIO.LOW) #小车右转函数 def right(): GPIO.output(IN1,GPIO.HIGH) GPIO.output(IN2,GPIO.LOW) GPIO.output(IN3,GPIO.LOW) GPIO.output(IN4,GPIO.LOW) #停止函数 def stop(): GPIO.output(IN1,GPIO.LOW) GPIO.output(IN2,GPIO.LOW) GPIO.output(IN3,GPIO.LOW) GPIO.output(IN4,GPIO.LOW) ##############小车前,后,左,右,停止测试############### #小车前进5秒 front() time.sleep(5) #小车后退5秒 back() time.sleep(5) #小车右转5秒 right() time.sleep(5) #左转5秒 left() time.sleep(5) #停止运行,并释放端口 stop() GPIO.cleanup()

Flask Framework Builds Server, Video Control Car

10.jpg
12.jpg
13.jpg

Flask framework structure analysis

app_car.py starts the Raspberry Pi server

The static folder stores CSS files

The templates folder stores the index.html file

other camera_pi.py is the camera library

called carcs.py is the

code to test the car

index.html is the control page displayed by the program at startup. It is written with its own text editor, and the code is not typeset.
The core statement is as follows: Set the page file for calling CSS in static img src="{{ url_for('video_feed') }}" width="50%">Specify the video stream and display it at 50% scale The web page uses the from control to communicate through the post method of the flask framework; it can also use ge or other methods #################Code attached #############################

I’m not very familiar with CSS format editing, so I’m cramming. The home page is displayed with yellow characters on a red background.
body{ background: red; color: yellow; }

Core code, app_car.py

from flask import Flask,request,render_template,Response # 导入flask框架所需要的模块
import RPi.GPIO as GPIO #导入RPi.GPIO库 import time #计时器 from camera_pi import Camera # #设置GPIO模式 GPIO.setmode(GPIO.BOARD) #设置in1到in4接口 IN1 = 11 IN2 = 13 IN3 = 15 IN4 = 16 #初始化接口 def init(): GPIO.setup(IN1,GPIO.OUT) GPIO.setup(IN2,GPIO.OUT) GPIO.setup(IN3,GPIO.OUT) GPIO.setup(IN4,GPIO.OUT) ''' 小车运动函数 ''' #前进 def front1(): GPIO.output(IN1,GPIO.HIGH) GPIO.output(IN2,GPIO.LOW) GPIO.output(IN3,GPIO.HIGH) GPIO.output(IN4,GPIO.LOW) #后退 def back1(): GPIO.output(IN1,GPIO.LOW) GPIO.output(IN2,GPIO.HIGH) GPIO.output(IN3,GPIO.LOW) GPIO.output(IN4,GPIO.HIGH)

#左转 def left1(): GPIO.output(IN1,GPIO.LOW) GPIO.output(IN2,GPIO.LOW) GPIO.output(IN3,GPIO.HIGH) GPIO.output(IN4,GPIO.LOW) #time.sleep(move_time) #GPIO.cleanup()

#右转 def right1(): GPIO.output(IN1,GPIO.HIGH) GPIO.output(IN2,GPIO.LOW) GPIO.output(IN3,GPIO.LOW) GPIO.output(IN4,GPIO.LOW) #time.sleep(move_time) #GPIO.cleanup()

def stop1(): GPIO.output(IN1,GPIO.LOW) GPIO.output(IN2,GPIO.LOW) GPIO.output(IN3,GPIO.LOW) GPIO.output(IN4,GPIO.LOW)

############################ # 固定写法 app = Flask(__name__) ############################ #摄像头函数调用了前辈写好的模块,后续再做解释 def gen(camera): """Video streaming generator function.""" while True: frame = camera.get_frame() yield (b'--frame \r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

@app.route('/video_feed') def video_feed(): """Video streaming route. Put this in the src attribute of an img tag.""" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') ############################# # 进入的首个网页 @app.route('/',methods=['GET','POST']) def main(): return render_template("index.html") # 返回网页

# 点击打开 @app.route('/front',methods=['POST']) def front(): front1() return render_template("index.html") #返回一开始的页面 # 点击关闭 @app.route("/back",methods=['POST']) def back(): back1() return render_template("index.html") #返回一开始的页面

@app.route("/left",methods=['POST']) def left(): left1() time.sleep(0.5) stop1() return render_template("index.html")

@app.route("/right",methods=['POST']) def right(): right1() time.sleep(0.5) stop1() return render_template("index.html") #返回主页 @app.route("/stop",methods=['POST']) def stop(): stop1() time.sleep(0.5) return render_template("index.html") #返回主页 if __name__=="__main__": init() #初始化GPIO端口 app.run(host='0.0.0.0',port=5000)#配置端口和IP GPIO.clearnup()