skip to Main Content

Requirements:

This video assumes you’ve got a Raspberry Pi that will work over Wi-Fi, a power source for the Pi, and that you’ve configured a microSD card for the Pi, installing the latest version of Raspbian Lite to work over Wi-Fi, and that you’ve installed CircuitPython libraries (videos demonstrate how to do this for use with the Adafruit Motor Hat and the Waveshare Motor Driver HAT). If you haven’t performed these steps, see videos in the tutorial at: videos for building an iOS-controlled Raspberry Pi robot, or the index of web-page tutorials that take you through the steps above.

This tutorial was written to install the mosquitto MQTT broker on a Raspberry Pi as part of a series of videos for building an iOS-controlled Raspberry Pi robot, but the steps below can be used to set up mosquitto on any Pi that’s running on a network. The tutorial assumes you’re using a Mac (which will be needed if you’re going to use write an iOS app to control the robot).

Video:

Prefer video instruction? Use the follow-along YouTube video that covers the steps, below.

Step 1: Upgrade and Install Necessary Software Before Installing Mosquitto

Log into your Pi.

  • Launch the Terminal program on your Mac by pressing Command-Space to launch Spotlight, then type Terminal, and press the return key.
  • Log into your Pi using the command below replacing hostname with your Pi’s hostname, then press the return key.
    ssh pi@hostname.local
  • Enter your Pi’s password when prompted, and press the return key.

It’s good practice to perform software upgrades before installing new software packages, so enter the series of commands below to make sure all of the software on your Pi is up to date and ready to support mosquitto. If you’ve recently completed the earlier videos in this series, then you’ll likely get messages that you’re up to date.

  • sudo apt-get update
  • sudo apt-get upgrade
  • sudo apt-get dist-upgrade

Step 2: Install Mosquitto and Python Libraries to Use MQTT in Python Programs

To install the mosquitto software for running MQTT on your Pi, enter the command below at the command prompt and press the return key. As always, select “Y” if asked if you’d like to continue, even though the operation will use additional disk space. NOTE: Some of the installations may seem like they are stalling at first, but after a minute or two you should see text showing installation progress.

  • sudo apt-get install mosquitto mosquitto-clients

Make sure you have python3-pip installed for installing additional software packages (if you followed earlier videos, you likely have this installed, but there’s no harm in entering the code below, and if you don’t need an upgrade you’ll quickly be returned to the command prompt).

  • sudo apt-get install python3-pip

Install the libraries for python support for MQTT by entering the command below and pressing the return key.

  • sudo pip3 install paho-mqtt

Verify that the mosquitto broker software is now running by typing the command below and pressing the return key.

  • systemctl is-active mosquitto
    

    You should see a message stating “active” if everything is working properly. If, for some reason, you don’t receive an “active” message, you can try rebooting your Pi, waiting about 30 seconds, login, then re-enter the command above.

Step 3: Use systemctl to Automatically Run mosquitto Each Time Your Pi Boots

Enter the command below and press the return key to ensure that the mosquitto broker runs automatically every time you boot your Pi (no need to ssh in or type additional commands). This is exactly what we’ll want if this Pi is dedicated to our robotics project – ideally we’d just turn our robot on and the software we need will begin running.

  • sudo systemctl enable mosquitto.service

You can verify everything is working by stopping your Pi with the command:

  • sudo halt
  • Then power your Pi off.
  • Turn your Pi on again.
  • Log back into your Pi using ssh
  • Then retype the command below and press the return key.
    systemctl is-active mosquitto

    You should see “active”, confirming that mosquitto has begun running on its own.

Step 4: Create a Subscriber Program to Listen for Robot Commands and Control to Our Robot

We’ll create a python program named control-pibot.py. This program will listen for messages from mosquitto. When it receives a message that it can use, it will respond by sending commands to our robot. For example, if the mosquitto broker receives a “forward” message from our iOS app, it will send the “forward” message to control-pibot.py, and this program will move our robot forward. Follow the steps below to create the control-pibot.py program:

  • From the Terminal, enter the command below, followed by the return key, to create an empty file in nano named control-pibot.py
    nano control-pibot.py
  • Open a browser and visit the GitHub repo at: https://github.com/gallaugher/pibot. This is a site that contains program files related to our robotics project.
  • Find the link labeled control-pibot.py and click it. A page will open showing all of the code for this python program.
  • Highlight and copy all of the lines in this python program.
  • Return to the Terminal and paste the program into nano.
    • IMPORTANT NOTE 1: ONLY if your Pi is named something other than “pibot” (for example, in the videos where I use the Waveshare Motor HAT, I named my Pi “zerobot”, then use the up arrow to move to the top of your code and find the line that reads:

      serverAddress = “pibot”

      Change “pibot” to the name of your Pi (e.g. “zerobot” in my example, above).

    • IMPORTANT NOTE 2: Only if you are using a Waveshare Motor Driver HAT, you need to make the same modification to this python program that we used in earlier videos when writing code to control our motors. You do not need to perform the step below if you are using an Adafruit motor hat, or other product that is natively compatible with CircuitPython.
      If you are using the Waveshare Motor Driver HAT, use the up arrow to move your cursor to the beginning of the code and find the line that reads:

      kit = MotorKit()
      then put a # character at the front of this line to comment it out.

    • Now use the down arrow to find the line that reads:

      # kit = MotorKit(0x40)
      and remove the # character and the blank space character before the word “kit“. This will uncomment this line, which is needed to use our code with the Waveshare Motor Driver HAT.

  • Exit nano by typing Control-X
  • Press the return key to save the file.

And at this point you should have a working MQTT subscriber running on the Pi that works in conjunction with the broker.

  • Run the program by typing the line below at the command prompt, then press the return key.
    python3 control-pibot.py

If everything is working you should see two messages:

subscribing

subscribed

You will NOT be returned to the command prompt in this terminal window because the program was run from within this window and it is continuing to execute.

If not, nano back into control-pibot.py and look at the line:

serverAddress = “pibot”

Make sure your Pi’s name is spelled correctly. Also examine any error messages for clues.

Step 5: Open a New Terminal Window then as a Test, Write a Command to “Publish” a Command to Move our Robot

  • From with the Terminal program, select the Shell menu, then New Window > New Window with Profile – Basic (or use the shortcut Command-N). This will open up another terminal window and return you to the command prompt.
  • From within this new window, enter the commands log in to your Pi using ssh (the same commands, Pi name, and password you’ve been using throughout this tutorial).

WARNING: The command below will start moving your bot forward, and you’ll need to enter another command to stop it. You might want to prop up your bot so the wheels aren’t touching the ground, otherwise be prepared to run after a runaway robot, and for it to possibly run into something.

  • Enter the command below and press return to send a “forward” command to the mosquitto broker. Mosquitto will then relay this command to the subscriber program (control-pibot.py), which will tell your bot to start moving forward.
    mosquitto_pub -h pibot.local -t "pibot/move" -m "forward"

    IMPORTANT NOTE: if your Pi is NOT named pibot, then change pibot.local to your Pi’s hostname. For example, in the videos where I used the Waveshare Motor Driver HAT, I had named my Pi zerobot, so the line should read zerobot.local. However, you should NOT  change the name in “pibot/move”.

  • Stop your bot by entering the command below, followed by the return key (as above, changing pibot.local to the name of your Pi if it’s not named pibot).
    mosquitto_pub -h pibot.local -t "pibot/move" -m "stop"

If everything works, congratulations – your Pi is now set up to listen for and act on commands sent to it over the Internet (and that’s what we’ll do in the next video when we write an iOS app to control the robot).

Also – you can close the Terminal window where you entered the mosquitto_pub commands above (you can click the “Terminate” button when closing this window), then look at the output in our first window. You should notice that underneat the “subscribing” and “subscribed” messages, there are now messages for “forward” and “stop”. We wrote control-pibot.py to print out these messages when it receives them, so this is a nice additional check that confirms that our python program is receiving messages as a subscriber to our mosquitto server.

Finally – let’s make sure control-pibot.py will run each time our Pi is started. To do this, follow the steps in the final section:

Step 6: Create a Service to Run control-pibot.py Automatically Whenver the Pi is Started

  • From the Terminal window, type Control-C to stop the execution of control-pibot.py. You can ignore the messages that show up as a result of stopping the program.
  • Enter the command below to begin creating a nano file with the name of the service we are going to create, then press the return key.
    sudo nano /lib/systemd/system/pibot-mqttclient.service
  • Open a browser window and return to the GitHub repo for the project at: https://github.com/gallaugher/PiBot
  • Find and click on the link for the file named: pibot-mqttclient-service. This will open a page containing code for the service we’ll write to automatically run control-pibot.py after the Pi starts.
  • Highlight all of the lines in the program in this file and copy them to the clipboard.
  • Return to the Terminal and paste the program into nano.
  • Type Command-X to exit nano, then the return key to save using the name we gave the file.
  • Enter the command below and press the return key to run this new pibot-mqttclient-service file whenever we start this Pi.
    sudo systemctl enable pibot-mqttclient.service

    You should see a verification message that says something like:

    Created symlink /etc/systemd/system/multi-user.target.wants/pibot-mqttclient.service → /lib/systemd/system/pibot-mqttclient.service

Step 7: Verify Everything is Working As Expected

  • Enter the command below and press enter to stop your Pi.
    sudo halt
  • Turn off the power to the Pi and the battery pack attached to the Motor HAT.
  • Wait a few seconds, then turn them both back on.
  • From Terminal, log back into your Pi using the standard ssh command, and enter your password.
  • At the prompt, enter the command below and press the return key.
    sudo systemctl is-active pibot-mqttclient.service

If everything is working you should see a message reading “active“. Congratulations! You’ve got an Internet-aware robot set up and ready to receive orders. Up next – create an iOS App to Control Your Robot!

Find the next document in this series and links to accompanying step-by-step YouTube videos at: https://bit.ly/iOS-Pi-Robot

❖    ❖    ❖    ❖    ❖

Ready for more? Check out tutorials on Robotics, Wearables, App Development and more at: http://bit.ly/GallaugherYouTube. Please consider subscribing and do share with others who may be interested!

Want to learn to build apps? The same content I use in my semester-long online course (videos and tutorial content) is available for less than $25 via links you’ll find at https://gallaugher.com/swift.

Look for more updates at gallaugher.com as well as on Twitter @gallaugher

Back To Top