DEV Community

medmor
medmor

Posted on • Updated on

Control rc car using raspberry pi (Part 2 : The web server)

Building the web server

In this part, we will start building the web server that will run on raspberry pi and will receive commands to control the rc car.

The framework used

We will use Bottle a lightweight web framework for python.
This is the first time I use python to build a web server and it was a very positif experience.
With Bottle.py, all you need is:

  • Create a file, I named it server.py.

  • Create a route.

  • And run the server.
    The minimal code needed to run a server is:

from bottle import route, run

@route('/')
def index():
    return "Hello world"

run(host='localhost', port=8080)
Enter fullscreen mode Exit fullscreen mode

To let other devices on the same network connect to the server, we will change the last line to run(host='0.0.0.0', port=8080)

Thats it, the server is running and can be accessed from other devices in the same network.

Create the routes

The routes could be implemented differently, but for simplicity we will use six routes :

  • Tree routes to control the front wheels: /right, /left and center.

  • Tree routes to control the rear wheels: /forward/<speed>, backward/<speed> and /stop. We use, in the tow first routes, a wildcard <speed>, to make the routes dynamic and change the speed of the car. The speed is an int that can change from 0 to 100, I will explain how to use it in the next parts.
    The code of the server.py is :

from bottle import post, route, run

@route("/")
def index():
    return "RC Car Server"


@route("/right")
def right():
    return "Car turning right"


@route("/left")
def left():
    return "Car turning left"


@route("/center")
def center():
    return "Car turning center"


@route("/forward/<speed>")
def forward(speed):
    return "Car running froward at speed : " + speed


@route("/backward/<speed>")
def backward(speed):
        return "Car running backward at speed : " + speed


@route("/stop")
def stop():
        return "Car stopped, the speed is : 0"

run(host="0.0.0.0", port=8080)
Enter fullscreen mode Exit fullscreen mode

Thats it for the server, we will improve it in next parts

Top comments (0)