Buttons for robot control

In this section, we will add implement buttons to the web interface to drive the robot.

  1. The first step is adding four buttons to index.html. We will be making use of HTML Table to add four buttons (Code snippet shortened for brevity and refer to http://www.w3schools.com/html/html_tables.asp for more information on HTML tables):
       <table style="width:100%; max-width: 500px; height:300px;"> 
<tr>
<td>
<form action="/forward" method="POST">
<input type="submit" value="forward" style="float:
left; width:80% ;">
</br>
</form>
</td>
...
</table>
  1. In web_interface.py, we need to implement a method that accepts POST requests from the buttons. For example, the method to accept requests from /forward can be implemented as follows:
       @app.route('/forward', methods = ['POST']) 
def forward():
my_robot.forward(0.25)
return redirect('/')
  1. Putting it altogether, web_interface.py looks something as follows:
       from flask import Flask, render_template, request, redirect 
from robot import Robot

app = Flask(__name__)
my_robot = Robot(1,2)

@app.route("/")
def hello():
return render_template('index.html')

@app.route('/forward', methods = ['POST'])
def forward():
my_robot.forward(0.25)
return redirect('/')

@app.route('/reverse', methods = ['POST'])
def reverse():
my_robot.reverse(0.25)
return redirect('/')

@app.route('/left', methods = ['POST'])
def left():
my_robot.left(0.25)
return redirect('/')

@app.route('/right', methods = ['POST'])
def right():
my_robot.right(0.25)
return redirect('/')

if __name__ == "__main__":
app.run('0.0.0.0')

The preceding code sample is available for download along with this chapter as web_interface.py (along with index.html). Add the following line to /etc/rc.local(before exit 0):

    python3 /<path_to_webserver_file>/web_interface.py

Reboot your Raspberry Pi Zero, and you should see a live feed of the robot's camera. You should also be able to control the robot from the browser!

Control your robot a browser!