Discover millions of ebooks, audiobooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

Programming Microcontrollers with Python: Experience the Power of Embedded Python
Programming Microcontrollers with Python: Experience the Power of Embedded Python
Programming Microcontrollers with Python: Experience the Power of Embedded Python
Ebook376 pages3 hours

Programming Microcontrollers with Python: Experience the Power of Embedded Python

Rating: 0 out of 5 stars

()

Read preview

About this ebook

For the first time microcontrollers are powerful enough to be programmed in Python. The landscape of embedded systems development is changing, microcontrollers are becoming more powerful, and the rise of the internet of things is leading more developers to get into hardware. This book provides the solid foundation to start your journey of embedded systems development and microcontroller programming with Python. 

You’ll quickly realize the value of using Python. The theme of the book is simplicity and the cleanness and elegance of Python makes that possible. Featuring a step-by-step approach, this single source guide balances complexity and clarity with insightful explanations that you’ll easily grasp. 

Python is quickly becoming the language of choice for applications such as machine learning and computer vision on embedded devices. What would previously be daunting and exceedingly difficult to do in C or C++ is now possible with Python because of its levelof abstraction. Programming Microcontrollers with Python is your path to bringing your existing skills to the embedded space.  

What You’ll Learn

  • Review microcontroller basics and the hardware and software requirements 
  • Understand an embedded system’s general architecture
  • Follow the steps needed to carry a product to market 
  • Take a crash course in Python programming
  • Program a microcontroller
  • Interface with a microcontroller using LCD and Circuit Python
  • Use and control sensors

Who This Book Is For

Those getting started with microcontrollers, those new to C, C++, and Arduino programming, web developers looking to get into IoT, or Python programmers who wish to control hardware devices.


LanguageEnglish
PublisherApress
Release dateMay 10, 2021
ISBN9781484270585
Programming Microcontrollers with Python: Experience the Power of Embedded Python

Related to Programming Microcontrollers with Python

Related ebooks

Hardware For You

View More

Related articles

Reviews for Programming Microcontrollers with Python

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Programming Microcontrollers with Python - Armstrong Subero

    © The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021

    A. SuberoProgramming Microcontrollers with Pythonhttps://doi.org/10.1007/978-1-4842-7058-5_1

    1. Getting Ready

    Armstrong Subero¹  

    (1)

    Basse Terre, Moruga, Trinidad and Tobago

    You have decided to learn about microcontrollers using Python. While it would be nice to jump straight into developing cool stuff, there are a few steps you must take to get ready first. If you have experience with software development, you may be accustomed to just opening an editor and typing code right away. However, microcontroller development is a little more involved than that. After all, you will be writing programs for a separate computer, so there is a lot more to set up. A microcontroller development environment consists of not only software but an entire hardware ecosystem that must be understood to unlock all the magic these devices have to offer.

    In this chapter, we will look at setting up an environment for development. By the end of the chapter, you will be ready to select a microcontroller board, and you’ll have the software tools and hardware devices needed to begin your development with CircuitPython. Let’s get started!

    Introduction to Microcontrollers

    In our modern world, computers are ubiquitous. They have become smaller, easier to use, and more integrated into our daily lives. A few years ago, to connect to the Internet and check your email, you would have had to sit down at a large desktop device. Today, you can do the same thing with a computer that fits in the palm of your hand and places all the information in the world at your fingertips.

    The advancements in technology that brought us smartphones and tablets have given billions of people access to computers. However, these handheld devices aren’t the only computers that exist. What if I told you that the billions of smartphones in use pale when compared to another kind of computing device that silently surrounds us? In fact, there are probably a half dozen or more of these devices in the room with you right now. These miniature computers are called microcontrollers , or MCUs, and they can be found all around us.

    Microcontrollers are small, intelligent, programmable computers that we use to perform tasks that are repetitive or that require some level of intelligent control without the need for human interaction. Microcontroller devices have a fraction of the computing power of a device like your smartphone or tablet, but they have many, many uses. Any device around you that reacts to a button press, displays information, or makes sounds when something is wrong is most likely controlled by a microcontroller. From calculators to TVs to microwaves and dishwashers, almost every household device you can think of contains a microcontroller.

    If you are familiar with computers, you are sure to have heard of a central processing unit (CPU) or a microprocessor: the brain behind your computer. A microprocessor lets a computer perform many functions. One day you might use your computer to type a document, the next to stream your favorite movie, and so on. The microprocessor has a lot of supporting circuitry, including memory and input and output chips, that allows it to carry out all these tasks. These are usually part of the motherboard that houses the microprocessor.

    A microcontroller takes all the supporting chips that are required to make a microprocessor work and places them on a single chip. This is why a microcontroller is called a single-chip computer . A microcontroller still operates like the microprocessor, but it is designed to only do a single task and to do it as efficiently as possible. For this reason, a microcontroller chip contains the minimum amount of processing power required to do its task.

    Firmware, Memory, and Clock Speed

    Like general-purpose computers, microcontrollers work by running programs. Because microcontrollers perform limited functions, the programs written for them are not expected to change frequently. For that reason, programs written for microcontrollers are called firmware. This firmware is usually stored as a binary file (with a .bin file extension) or a hex file which is a text-represented binary file (having a .hex file extension); this file contains the memory content that is written on flash, and thus it is ready to be run on the microcontroller. A special device called a programmer loads this binary file into the microcontroller’s memory.

    The memory consists of two parts: the main memory (sometimes called program memory) and the random-access memory (RAM, sometimes called data memory). The main memory is nonvolatile, whereas RAM is volatile. This means that when the microcontroller is not powered, the information contained in RAM will disappear, whereas the information in the main memory will be retained. For this reason, the main memory is also called read-only memory (ROM). Its contents are designed to be mainly read, whereas RAM is designed to have its contents changed by the user during runtime.

    In a general-purpose computer system, usually a program is loaded into RAM before it is executed. Microcontroller systems are a bit different. In a microcontroller, the firmware is executed directly from ROM, and RAM is used to do things such as to store temporary information that aids in running the firmware (these are usually runtime variables and can contain a stack or a heap, special memory structures).

    Some microcontroller devices can have their ROM contents programmed into them from the factory and cannot be changed by the end user once they are put into a device. These are called one-time programmable (OTP) devices, and they are cheaper and easier to manufacture. Usually though, the ROM is made of flash memory, meaning that it can be programmed and changed after manufacturing.

    Flash memory lets you program a device thousands of times, making it useful for learning and product prototyping. If errors show up in your firmware program, flash also allows you to fix errors by means of an update, a process called patching. Updates usually take the form of over-the-air (OTA) updates, which change the contents of the ROM via a wireless connection. OTA updates are common for Internet of Things (IoT) devices. Alternately, you can connect the device to a computer with a cable to update the firmware.

    A microcontroller executes the instructions in its firmware program according to the speed of a clock that runs the device. The speed is measured in hertz, or cycles per second. The faster the clock speed , the faster the device will execute instructions. Microcontroller clock speeds typically range from about 1 MHz (though for extremely low-cost, low-power applications, the clock speed can run as low as 32.768 kHz to about and for fast systems up to 1 GHz.)

    8-Bit vs. 32-Bit

    The devices we will use in this book are quite powerful. They consist of a 32-bit microprocessor core which means that the number of bits of data that can be processed by the microcontroller is comprised of 32 registers (a register is a small storage location for data within the microcontroller; we’ll talk about this more in the next chapter). For a long time, however, 8-bit devices ruled the microcontroller market.

    Historically, 32-bit devices were expensive and hard to program. Due to advances in technology, the cost of 32-bit devices has been declining to the point of where they can rival 8-bit devices for all but extremely cost-sensitive applications. Meanwhile, thanks to the myriad of tools now available to use with them, 32-bit devices have become amazingly easy to program and control. While 8-bit microcontrollers are still alive and relevant, a lot of their market share is being replaced by 32-bit devices.

    For beginners, 32-bit devices are an especially useful learning tool because they contain more memory and have greater memory addressing capabilities. This allows for a higher level of abstraction, meaning it is typically easier to program a 32-bit device without a thorough understanding of its inner workings. By contrast, since 8-bit devices have less processing power and memory, you need to have a deeper understanding of the internals of the device to better manage memory resources and write effective programs.

    Microcontroller Programming Languages

    In this section, we will look at some of the languages available for programming microcontrollers. While there are several options to choose from, microcontrollers have been mostly resistant to the overcrowded zoo of programming languages that make up the modern software development landscape. Historically, the microcontroller world has been dominated by the C programming language. This is because microcontrollers have traditionally only had a few bytes of memory and run at a few tens of megahertz of clock speed, and C is particularly well suited to working on memory-constrained systems. Nowadays, though, you can find microcontroller devices that have multiple cores that run up a gigahertz and possess several megabytes of memory, opening up space for other languages to be used.

    Assembly Language

    At one point in time, microcontrollers were programmed exclusively in assembly language. Today, assembly language is reserved for devices with limited memory and for situations where the programmer needs to squeeze every drop of performance out of the microcontroller. Assembly language is useful in these situations because a lot of assembly instructions translate directly into machine instructions on the microcontroller. This means that there is less overhead in the execution of the instructions, making code segments written in assembly language faster. While assembly language is fast, it takes a lot of instructions to perform a simple task on the device. Another limiting factor of assembly language is that for each device you are programming, you must learn the assembly language for that device. Given these limitations, the language has declined in popularity for all but niche situations.

    C

    C has long been the language of choice in the embedded world. It was made to run on memory-constrained devices such as microcontrollers. C gives us the ability to control the underlying hardware efficiently – one C instruction translates into several assembly language instructions – and it can match the speed of assembly language for most applications. Since C has been used for so long, a lot of the code that is written has been battle tested and proven to work for the applications they are intended. C users have access to a large code base with helpful information and code snippets. However, the language requires a good understanding of the hardware and is difficult for beginners to break into.

    C++

    As time progressed and embedded devices became more powerful, some microcontroller manufacturers and software vendors began adding C++ support to their devices. C++ is slowly gaining traction in the professional embedded space. In the hobbyist realm, however, C++ finds widespread use on the Arduino platform. C++ is a large and difficult language to learn, however. Many of the features that make C++ more effective to use than C in general-purpose computing applications, sometimes cannot be implemented on the resource-constrained microcontroller devices. This is because while C++ can match the performance of C for most applications, C++ tends to use more memory, a precious resource that is usually not bountiful on microcontroller devices. For that reason, C++ is reserved for the higher-end devices.

    BASIC

    In the early 2000s, if a beginner was getting started with microcontrollers and did not fancy assembly, BASIC was the programming language to use. BASIC stands for Beginners’ All-Purpose Symbolic Instruction Code and is an easy programming language to use. There would usually be a BASIC interpreter on the microcontroller chip to run the instructions.

    BASIC eventually fell in popularity because the boards that ran it cost a lot of money relative to what they were capable of. Additionally, running the BASIC interpreter slowed the chips down and took up too many resources on the already constrained 8-bit devices. Also, the tools and software for the most popular BASIC devices were all closed source, so people could not make their own BASIC devices. When open source alternatives like the Arduino came around, devices like the BASIC Stamp thus fell out of favor.

    Rust

    The Rust programming language is new compared to C (which is almost half a century old) and is designed to upset the C and C++ hold on systems programming, including embedded programming. As microcontrollers become more powerful and factors like concurrency (the ability to carry out multiple processes at once) start to matter, Rust’s advantages over C begin to show. Rust is better suited to concurrency because it can handle a data race, which is when two devices try to access the same location in memory at the same time.

    While Rust could replace C, there is no reason for the industry to adopt it anytime soon. Embedded software is called firmware for a reason: it doesn’t change all that often, and much of the code that has already been written has no reason to change to a new language. C works and has a lot of established toolchains and devices, and there are many skilled developers comfortable with the language. However, there are already tools available that allow Rust to be used on microcontrollers, and as time progresses, Rust may gain some share in the embedded market.

    Python

    Python is a relative newcomer to the embedded space, and it could become a major player in the field. Python is a lot simpler than C to learn and is one of the most popular programming languages today. While BASIC was also easier than C for beginners, Python has several advantages over BASIC that make it better suited for use as an embedded language. Notably, while the popular BASIC microcontrollers were closed source, Python is open source, allowing you to run Python on your custom device if you desire. Python files can also be compiled to make them smaller, allowing you to create tight, memory-efficient programs.

    Many people say that interpreted languages like Python are not suited to the limitations of microcontrollers. This may have once been true, but with today’s more powerful devices, it is entirely possible for microcontrollers to run interpreted languages without hiccups like the speed limitations experienced by older BASIC devices. For extremely time-efficient computing, also called real-time computing, interpreted languages are still not suitable. However, Python should have no problem meeting the speed requirements of the majority of microcontroller projects.

    While Python is not as fast or efficient as C when running on microcontrollers, its ease of use makes it worthwhile, especially if you are now getting started with microcontrollers. Additionally, you can extend Python code with C, which means you can leverage existing C code bases that have been battle tested and refined over the decades.

    The Python interpreter as it exists on general-purpose computers cannot be directly implemented on a microcontroller with the same available features. This is because the standard Python interpreter is a large program that relies on features that would be given by the operating system, particularly memory and hardware interfacing features, a luxury nonexistent on microcontroller devices. Two modified forms of the language interpreter, MicroPython and CircuitPython, bridge the gap between the standard Python interpreter and the embedded space. Of the two, MicroPython is targeted more toward professional developers and precedes CircuitPython. CircuitPython, developed by Adafruit, is simpler to use, making it an excellent learning tool for beginners as well as a platform for professionals. The major feature of CircuitPython that makes it user-friendly is that you do not need to compile a program before it can run on the microcontroller. As soon as you save a program, it is run and executed.

    CircuitPython promises to be available for more resource-constrained devices and is expected to remain well supported into the foreseeable future. For these reasons, we will use it throughout this book.

    Selecting a Development Board

    To work on the projects in this book, you will need a development board with a microcontroller that can run CircuitPython. A development board contains a microcontroller as well as the connections required to power the board and get it up and running. A development board allows you to use, program, and prototype with the microcontroller without worrying about the hardware setup.

    At the time of writing, CircuitPython supports over 140 boards, and the list keeps growing. You can view the list here on the CircuitPython website: https://circuitpython.org/downloads. Any one of these compatible boards will work with this book. You can also choose to create your own custom device that supports CircuitPython, a process I will discuss at the end of this chapter. For beginners, however, using a premade, CircuitPython-compatible board will always be a better choice. It will ensure that the hardware is working and allow you to get started more quickly with writing software for your device.

    In this section, we will look at some preconfigured devices that can run CircuitPython. Though many companies supply microcontroller boards that are capable of running CircuitPython, Adafruit devices have the best support since they originated the language and have an entire ecosystem built around CircuitPython with their development environment. We’ll look at some of the boards that they have available, along with some popular boards from other manufacturers that can be used with CircuitPython. This list is not exhaustive, but the boards presented here will be compatible with the examples discussed in this book.

    Adafruit Metro M0 Express

    The first board we will look at is the Adafruit Metro M0 Express, pictured in Figure 1-1. This board is an ideal choice to be used with the examples in this book, as it is powered by a SAMD21G18A microcontroller. This board also has the Arduino form

    Enjoying the preview?
    Page 1 of 1