Gerd Altmann, Pixabay
Programmer Promo 5ed814f7a87a8

How to Program Hardware with MicroPython: A Beginner’s Guide

June 4, 2020
C isn’t the only programming language for microcontrollers. This article covers the compatible hardware and workflow steps when programming with a different option—MicroPython.

This article is part of  MicroPython for Embedded Systems in the MicroPython for Embedded Systems

MicroPython is a compact implementation of the Python 3 programming language designed to work with microcontrollers. Initially announced back in 2013 as part of a Kickstarter project created by Damien George, MicroPython eventually became one of the preferred firmware options for microcontroller programmers and enthusiasts alike. Damien ended up created his own line of hardware that comes equipped with MicroPython right off the bat. However, the firmware can also be installed on a wide range of other boards.

If you’re interested in making a career out of hardware programming or simply want to do it as a hobby, you’ll have a lot to gain by learning how to work with MicroPython. In this beginner’s guide, we’re going to teach you the basics about compatible hardware and workflow, as well as show you a couple of practical examples of how a microcontroller can be programmed with the help of MicroPython. Without further ado, let’s jump right into it.

MicroPython Hardware

If you’re ready to give MicroPython a chance, it’s time to start looking into some hardware options. Plenty of boards out there are compatible with the programming language, but as it’s often the case with these types of things, some products are a bit better than others. And, of course, some are much more expensive than others. Picking the right board for your project is very important, so let’s take a look at a few of the most solid options available on the market right now.

The Pyboard

The Pyboard was developed and optimized by Damien George and some of the other developers that contributed to the MicroPython project. As such, it’s arguably the best option if you’re looking for a specialized board to work with MicroPython. If you head over to the MicroPython store, you’ll find various Pyboards to choose from along with housings, skins, adapters, and peripherals.

Pyboards are based on the STM32 series of microcontrollers and come equipped with a Cortex-M4F CPU and 128k of RAM or more, depending on the model. Other highlights include a micro USB connector, micro SD card slot, and an accelerometer, among other features.

ESP32

ESP32 is a high-performance, low-cost series of microcontrollers that come with a wide variety of features, including built-in Wi-Fi and Bluetooth capabilities. The specs include 520k SRAM and a CPU clocked at either 160 or 240 MHz, depending on the model. The ESP32 boards are quite powerful for their size and feature lots of extras like power-management modules, antenna switches, power amplifiers, filters, and more.

Though the price of the chip itself is quite affordable, you may have to purchase the various modules separately and there are many to choose from. Not necessarily the best choice for beginners, but if you know what you’re doing, the ESP32 can definitely get the job done. If you’re looking for a cheaper option and don’t mind missing out on some features, you may want to check out ESP32’s predecessor, the ESP8266 series.

BBC Micro:Bit

The Micro:Bit is an open-source Arm-based microcontroller designed primarily for educational purposes. The compact device is quite popular in the U.K., where it was freely distributed to over 1 million British teachers and students back in 2016. Despite its small size, the board comes equipped with an impressive array of features, including an accelerometer, Bluetooth connectivity, microUSB, two programmable buttons, edge connector, and more. The Micro:Bit is aimed at children between the ages of 7 and 14, but you can definitely made good use of the board even if you’re a lot older.

CircuitPython

CircuitPython is a project that’s quite similar to MicroPython in the sense that it was also designed to make hardware programming as simple and as accessible as possible. CircuitPython is fully compatible with the Pyboard, as well as a wide variety of other microcontrollers, including a number of boards developed by open-source hardware company Adafruit. The company’s flagship board goes by the name of Circuit Playground Express and comes equipped with all of the features a beginner needs to get started with hardware programming. A few of the highlights include motion sensor, temperature sensor, mini speaker with class D amplifier, infrared receiver, RGB LEDs, USB port, and more.

MicroPython Workflow

Getting started with hardware programming may seem intimidating at first glance, but working with MicroPython is actually pretty straightforward. That’s because MicroPython comes with a handful of tools that greatly simplify the whole process.

REPL

REPL (read-eval-print loop) is an interactive programming environment that takes user inputs and returns results after evaluating them. Depending on the type of hardware you’re working with, you may have MicroPython along with REPL already installed on your device. If not, you can start up a REPL session in one of two ways. The simplest way is to use the WebREPL on the official MicroPython website and establish a connection with your microcontroller. However, this only works with boards that support Wi-Fi.

The second method involves using a serial terminal connection. Linux users would probably be most familiar with this process. However, you can start a serial REPL session regardless of your operating system. If you’re using Linux, simply open the terminal and type the command below to get a list of active serial connections.

  $ ls /dev/tty.*

Take a look at the list and make note of your device’s name and baud rate. Then, add them both at the end of the command mentioned earlier. If you’re on MacOS and you’re using the Screen application as your terminal, the command will look something like this:

  $ screen /dev/tty.wchusbserial1430 115200

If you’re on Windows, on the other hand, a bunch of terminal emulators are available to try, including Cmder, Terminus, Xshell, and of course, PuTTY, which is the go-to program for most users.

Once your REPL connection is established, you can enter and execute commands using the interactive prompt. MicroPython’s REPL was designed with accessibility in mind and as such, includes some very useful features like tab completion, paste mode, history, auto-indent, and more.

Command-Line Tools

The pyboard.py is a standalone tool that lets you run Python scripts or commands on a MicroPython device and includes a few other neat features. While the tool was designed to work with the Pyboard, it’s also compatible with other microcontrollers that support the raw REPL. This includes the ESP32 and ESP8266 series, which we mentioned in one of the previous sections. A few other useful command-line tools you may want to try are RShell, Upydev, and Ampy.

Integrated Development Environments (IDEs)

A bunch of plugins let you add MicroPython support to your interactive development environment. If you’re working with PyCharm, which is available on Windows, Linux, and macOS, you can go directly to the marketplace to find a plugin known simply as MicroPython. Mu Editor and uPyCraft are a couple of other good options you may want to look into. Regardless of which plugin you use, you’ll need to connect to your device using the serial port. If everything goes well, you’ll be able to interact with the MicroPython REPL from IDE.

How to Install MicroPython on Your Board

If you’re going with something like the Pyboard, you won’t have to worry about this step because those types of boards come pre-installed with MicroPython by default. Meanwhile, other boards, especially those developed by Adafruit, will likely feature CircuitPython instead, which is also a very good choice for hardware programming. But if your microcontroller doesn’t already have MicroPython on it, there’s no need to worry because you can install the firmware yourself.

Probably the easiest way to get MicroPython on your board is to use the uPyCraft IDE. You can potentially get a two-for-one deal here because the application can also be used to program boards, though it’s primarily optimized for ESP32 and ESP8266 variants. The steps for installing MicroPython using uPyCraft are as follows:

1. Start by installing the software on your computer and then go to the official MicroPython website to download the correct firmware for your particular board. Connect your microcontroller to your computer and proceed to the next step.

2. Open uPyCraft and go to Tools -> Boards. Select the appropriate option from the list. For example, if you’re using an ESP32-based board, you should see one of the options labeled as “esp32”. If your board is connected but you don’t see it on the list, make sure your USB drivers are up-to-date.

3. Access the Tools menu again, but this time select the option “BurnFirmware”. A new window will appear where you can customize the installation. If you’re using an ESP32 microcontroller, you’ll want to choose the following options:

  • board: esp32
  • burn_addr: 0x1000
  • erase_flash: yes
  • com: COM5

Some of these options may differ depending on your board, so make sure to check the documentation if you’re using a different microcontroller.

4. Your next order of business is to choose the firmware you want to install. Under “Firmware Choose,” select the “Users” option and then click the “Choose” button. Navigate to the Downloads folder to find and select the MicroPython file you downloaded earlier.

5. Hold down the BOOT button (name may differ depending on your board) on your microcontroller and, at the same time, click the “OK” button in the uPyCraft window. Once the firmware installation starts, you can release the BOOT button. The installation process should only take a few seconds, after which you should be good to start programming your board.

How to Create and Deploy Code

The process of deploying code on your MicroPython board is similar to how things work when you’re using regular Python. Namely, you’ll need to create .py text files containing your code, transfer them to the microcontroller, and then execute them. The only difference is that you’ll need to transfer the files from your computer to your board, which can be accomplished in two ways:

1. Using an IDE:  uPyCraft, Mu Editor or any other similar application will do the trick.

2. Using a command-line tool: Any of the tools mentioned earlier should work, including pyboard.py, RShell, Upydev, and Ampy.

If you prefer working with the REPL prompt instead, you can execute .py text files by typing in the following command in the terminal:

  exec(open('my-program.py').read())

How to Write MicroPython Code

Your first little project can be the classic “Hello, World!” This simple project is great for checking if everything is working as it should. Simply go to the REPL and type in the following:

  print("Hello World!")

If the prompt outputs the words “Hello World!”, you can be sure that your connection works and you can move on to more interesting projects. You can check out a few great projects on the official MicroPython website. Simply select a project, copy the code, and then paste it into your terminal before running the script.

How to Program a Blinking LED

Printing text is all fine and dandy, but let’s try something a bit more advanced, like making the onboard LED blink. To do that, paste in the code below.

  import time
  machine  
  blueled = machine.Pin(2, machine.Pin.OUT)
  
  # Blink 10 times
  for i in range(1,11):
      blueled.value(0)
      time.sleep(0.5)
      blueled.value(1)
      time.sleep(0.5)
  print("DONE!")  

 Running this script will import the time and machine modules, which let you add delays and access the IO pins on the microcontroller. With this piece of code, you set up an object called blueled and define it as Pin 2. Depending on your board, you may have to give Pin a different numerical value. The second part of the code dictates the blinking pattern, i.e., how many times the LED should blink and for how long.

The project above only works with microcontrollers that have built-in LED lights. Most boards on the market do include at least one LED, but some don’t have any. You can still run the project even in those cases, but you’ll need to connect an external LED coupled with a resistor. Working with external components can be a lot of fun, but it does require more technical know-how. If you’re not comfortable with this just yet, you may want to invest in a board that comes with built-in LEDs.

How to Program a Fading LED

The LEDs on your board, or those connected to it, can do more than just blink. In fact, you can program a variety of patterns and effects by simply running a different script. In the next example, you import the PWM (Pulse Width Modulation) module to set the brightness of the LED. Feel free to experiment by choosing different values for the brightness and frequency in the code below.

  from machine import Pin
  from machine import PWM
  import time
  
  # Set our pin 2 to PWM
  pwm = PWM(Pin(2))
  
  # Brightness between 0 and 1023
  pwm.duty(700)
  
  # Frequency in Hertz
  pwm.freq(1)

If you want the LED to fade in and out, you’ll need to add a few more lines to the code by combining it with the time module mentioned in the very first example. Again, feel free to experiment with the different values.

  from machine import Pin
  from machine import PWM
  import time
  
  # Set our pin 2 to PWM
  pwm = PWM(Pin(2))
  
  # Frequency = 100hz
  pwm.freq(100)
  
  while 1:
    # Brightness between 0 and 1023
    for brightness in range (0, 1023, 100):
      pwm.duty(brightness)
      print(brightness)
      time.sleep(0.1)
    # Brightness between 1023 and 0
    for brightness in range (1023, 0, -100):
      pwm.duty(brightness)
      print(brightness)
      time.sleep(0.1)

For easy access to this code, you can upload and download it at any time by using a hosting service from the likes of Bluehost or GoDaddy. Doing so will allow you to bypass the hassle of using a USB drive every time you want to upload the code to your microcontroller.

Final Thoughts

For the longest time, programming hardware was primarily done by using scripting languages like C++ and assembler, but that’s no longer the case these days. Thanks to MicroPython, pretty much anyone can now program microcontrollers, robots, and a wide variety of other devices. All you need is a device that’s compatible with the language, a few scripts, and maybe an application or two depending on the complexity of your project.

MicroPython is often used for small-scale projects. However, you will be able to take on more complex tasks that involve multiple devices once you’ve got a bit of experience under your belt. Until then, continue experimenting with small things and make sure to keep an eye on the MicroPython community if you want to stay up to date with all the newest projects, tools, and tutorials created by developers and MicroPython enthusiasts.

This article is part of  MicroPython for Embedded Systems in the MicroPython for Embedded Systems

About the Author

Jason Moth

Jason developed a keen interest in computer programming when he was but a wee lad and his passion for the topic grew steadily ever since. While he enjoys writing about most scripting languages and all of the amazing projects created with their help, Python is undoubtedly his one “true love."

Sponsored Recommendations

Comments

To join the conversation, and become an exclusive member of Electronic Design, create an account today!