DIY Microcontroller Projects for Hobbyists - Miguel Angel Garcia-Ruiz - E-Book

DIY Microcontroller Projects for Hobbyists E-Book

Miguel Angel Garcia-Ruiz

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

We live in a world surrounded by electronic devices, and microcontrollers are the brains of these devices. Microcontroller programming is an essential skill in the era of the Internet of Things (IoT), and this book helps you to get up to speed with it by working through projects for designing and developing embedded apps with microcontroller boards.

DIY Microcontroller Projects for Hobbyists are filled with microcontroller programming C and C++ language constructs. You'll discover how to use the Blue Pill (containing a type of STM32 microcontroller) and Curiosity Nano (containing a type of PIC microcontroller) boards for executing your projects as PIC is a beginner-level board and STM-32 is an ARM Cortex-based board. Later, you'll explore the fundamentals of digital electronics and microcontroller board programming. The book uses examples such as measuring humidity and temperature in an environment to help you gain hands-on project experience. You'll build on your knowledge as you create IoT projects by applying more complex sensors. Finally, you'll find out how to plan for a microcontroller-based project and troubleshoot it.

By the end of this book, you'll have developed a firm foundation in electronics and practical PIC and STM32 microcontroller programming and interfacing, adding valuable skills to your professional portfolio.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 326

Veröffentlichungsjahr: 2021

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



DIY Microcontroller Projects for Hobbyists

The ultimate project-based guide to building real-world embedded applications in C and C++ programming

Miguel Angel Garcia-Ruiz

Pedro Cesar Santana Mancilla

BIRMINGHAM—MUMBAI

DIY Microcontroller Projects for Hobbyists

Copyright © 2021 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author(s), nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Richa Tripathi

Publishing Product Manager: Shweta Bairoliya

Senior Editor: Storm Mann

Content Development Editor: Kinnari Chohan

Technical Editor: Karan Solanki

Copy Editor: Safis Editing

Project Coordinator: Deeksha Thakkar

Proofreader: Safis Editing

Indexer: Tejal Daruwale Soni

Production Designer: Nilesh Mohite

First published: June 2021

Production reference: 1290621

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80056-413-8

www.packt.com

To my parents, Rosa and Miguel, for giving me the love to learn new things. To my wife, Selene, and my son, Miguel, for their support, love, and inspiration.

– Miguel Garcia-Ruiz

To my son, Max, for his love and inspiration, and for making my life memorable by calling me daddy. To my wife, Abi, for her love, inspiration, and unconditional support. To my mom, Lety, and my brother, Jesús, for their love and always being there.

– Pedro Cesar Santana Mancilla

Contributors

About the authors

Miguel Angel Garcia-Ruiz is an Associate Professor of Computer Science at the School of Computer Science and Technology, Algoma University, Canada. He has taught microcontroller programming and interfacing, human-computer interaction, and interaction design courses. Miguel has a PhD in Computer Science and Artificial Intelligence from Sussex University, England. He has published articles on tinkering with technology applying microcontroller boards. Miguel has conducted research projects funded by Canada's Northern Ontario Heritage Fund (NOHFC), Algoma University, and the Mexican Ministry of Education.

I want to thank the friends and family, who have been close to me and supported me, especially my wife and my son.

Pedro Cesar Santana Mancilla is a research professor at the School of Telematics at the University of Colima in Mexico. His research interests focus on human-computer interaction, ICT for elderly people, Internet of Things, and machine learning. He is currently serving as president of the Mexican Association on Human-Computer Interaction (AMexIHC). He is a Senior Member of the IEEE, and ACM and serves as Chair of the Mexican ACM SIGCHI Chapter (CHI-Mexico). Pedro is a member of the Mexican Academy of Computing (AMexComp) and the Mexican Society of Computer Science (SMCC).

I want to thank my family and friends, who have always supported me. A special thank you to my wife and son for all their support and patience during the long process of writing this book. Thanks also to Prof. Fermín Estrada for his help in resolving my doubts.

About the reviewers

Darshan Jivrajani is an electronics and communication engineer. He has more than 4 years of experience as an embedded system engineer. In his career, he has completed and has been a part of many projects, including smart switches, smart parking systems, indoor navigation, small computers, TV lifting, and many more. He is familiar with ESP32/8266, PIC, Cypress, NXP, Atmel AVR, Stm32, Raspberry Pi, Beaglebone Black, NRF, BLE4.0/5.0/5.1 microcontroller families. On another side of programming, he is comfortable with embedded C/C++, Python, Node.js, and various communication protocols, such as TCP/IP, UDP, Socket, MQTT, CoAP, I2C, UART, USART, I2S, WiFi, Bluetooth, Zigbee, GPS/GSM, Nb-IoT, Lora, Z-wave, and more.

Paras Balasara is an embedded hardware engineer who creates and brings life to hardware that interacts with sensors through a power supply.

Table of Contents

Preface

Chapter 1: Introduction to Microcontrollers and Microcontroller Boards

Technical requirements

Introduction to microcontrollers

Microcontroller boards

An overview of analog and digital electronics necessary for carrying out the book's projects

Basic electronic components

The diode

The solderless breadboard

Description of the Blue Pill and Curiosity Nano microcontroller boards

Installing the IDEs

Your first project – a blinking LED

Running the blinking LED example with the Blue Pill board

Running the blinking LED example on the Curiosity Nano board

Summary

Further reading

Chapter 2: Software Setup and C Programming for Microcontroller Boards

Technical requirements

Introducing the C programming language

The basic structure of the C language

Introducing Curiosity Nano microcontroller board programming

Introducing Blue Pill microcontroller board programming

Example – Programming and using the microcontroller board's internal LED

Programming the Blue Pill's internal LED

Summary

Further reading

Chapter 3: Turning an LED On or Off Using a Push Button

Technical requirements

Introducing push buttons

Understanding electrical noise from push buttons

Debouncing a push button via hardware

Debouncing a push button via software

Connecting an LED to a microcontroller board port and using an internal pull-up resistor

Debouncing a push button via software connected to the Blue Pill

Turning an LED on or off with a push button on the Curiosity Nano

Testing out the push button

Summary

Further reading

Chapter 4: Measuring the Amount of Light with a Photoresistor

Technical requirements

Understanding sensors

Defining sensors

What are sensor modules?

Introducing photoresistors

Connecting a photoresistor to a microcontroller board port

Connecting a photoresistor to a Blue Pill board

Coding the photoresistor values and setting up ports

Connecting a photoresistor to a Curiosity Nano board

Connecting a photoresistor sensor module to the microcontroller boards

Testing out the photoresistor

Summary

Further reading

Chapter 5: Humidity and Temperature Measurement

Technical requirements

Introducing the DHT11 humidity and temperature sensor module

What is relative humidity?

The DHT11 pins and their values

Connecting a DHT11 sensor module to the microcontroller boards

Connecting the DHT11 to the Blue Pill board

Connecting an LCD to the Blue Pill

Connecting an LM35 temperature sensor to the Curiosity Nano board

Coding to get data from the sensor module

Programming the DHT11 sensor for the Blue Pill board

Coding the sensor module and the 1602 LCD

Programming the LM35 sensor on the Curiosity Nano board

Showing the humidity and temperature data results on the serial port monitor

Plotting the data

Summary

Further reading

Chapter 6: Morse Code SOS Visual Alarm with a Bright LED

Technical requirements

Understanding Morse code and the SOS message

Introducing super-bright LEDs and calculating their necessary resistors

Connecting the resistor and the super-bright LED to the microcontroller board

Connecting the super-bright LED to the Curiosity Nano

Coding the SOS Morse code signal

The SOS message code for the Curiosity Nano

Testing the visual alarm

Summary

Further reading

Chapter 7: Creating a Clap Switch

Technical requirements

Connecting a microphone to a microcontroller board port

Understanding the electret microphone module

Connecting the components

Coding your clap switch sketch

Coding a clap switch with two clapping sounds

Coding a clap switch with a timer between claps

Improving the project performance

Summary

Further reading

Chapter 8: Gas Sensor

Technical requirements

Introducing the MQ-2 gas sensor

Connecting a gas sensor to the STM32 microcontroller board

Interfacing for digital reading

Interfacing for analog reading

Writing a program to read the gas concentration over the sensor board

Coding for digital reading

Coding for analog reading

Testing the system

Summary

Further reading

Chapter 9: IoT Temperature-Logging System

Technical requirements

Connecting a temperature sensor to the Blue Pill board

Introducing the DS18B20 temperature sensor module

Connecting the components

Coding a temperature reading system

Learning to connect the ESP8266 module

An introduction to the ESP8266 Wi-Fi module

Connecting an ESP8266 Wi-Fi module

Coding a program to send the sensed temperature to the internet

Connecting the STM32 Blue Pill board to the internet

Summary

Further reading

Chapter 10: IoT Plant Pot Moisture Sensor

Technical requirements

Connecting a soil moisture sensor to the Blue Pill board

Introducing soil moisture sensors

Connecting the components

Reading data from the soil moisture sensor module

Coding a program to send the sensed data to the internet

Showing sensor data results over the internet

Summary

Further reading

Chapter 11: IoT Solar Energy (Voltage) Measurement

Technical requirements

Connecting a solar panel to the Blue Pill board

Introducing the solar panel

The B25 voltage sensor

Connecting the components

Reading data from a voltage sensor module

Coding a program to send the sensed data to the internet

Showing sensor data results over the internet

Summary

Further reading

Chapter 12: COVID-19 Digital Body Temperature Measurement (Thermometer)

Technical requirements

Programming the I2C interface

The I2C protocol

I2C coding

Coding the Arduino Uno software (peripheral)

Coding the Blue Pill software (controller)

Connecting an IR temperature sensor to the microcontroller board

The MLX90614 IR sensor

The GY-906 sensor module

Connection of the IR sensor to an Arduino Uno

Connecting the Blue Pill to the Arduino Uno

Showing the temperature on an LCD

Testing the thermometer

Summary

Further reading

Chapter 13: COVID-19 Social-Distancing Alert

Technical requirements

Programming a piezoelectric buzzer

Connecting the components

Connecting an ultrasonic sensor to the microcontroller board

Connecting the components

Writing a program for getting data from the ultrasonic sensor

Testing the distance meter

Summary

Further reading

Chapter 14: COVID-19 20-Second Hand Washing Timer

Technical requirements

Programming the counter (timer)

Showing the timer on an LCD

Connecting an ultrasonic sensor to the microcontroller board

What is an ultrasonic sensor?

How does an ultrasonic sensor work?

Putting everything together – think of a protective case for the project!

Testing the timer

Summary

Further reading

Other Books You May Enjoy

Preface

This book will introduce you to microcontroller technology. It focuses particularly on two very capable microcontroller boards, the Blue Pill and the Curiosity Nano, and how to connect sensors to them to solve problems and to support everyday life situations. In addition, this book covers the use of light-emitting diodes (LEDs) and liquid-crystal displays (LCDs) for showing sensor information to its microcontroller board users.

Microcontroller boards are practical small computers used for getting information from an environment using sensors. In this book, each chapter will focus on a specific problem to be solved with microcontroller technology, incorporating the use of practical sensors.

Many people from the intended audience would like to start with a microcontroller-based project but they may not know how to begin with it, including what kind of basic hardware and software tools and electronic components they will need to use. This book will cover that.

A chapter in this book introduces you to the field of electronics, examining and reviewing common electronic components that you will use in this book. Another chapter provides an introduction to C and C++, which will be used for coding Blue Pill and Curiosity Nano applications in most of the chapters.

One of the most important aspects of this book is that sensor programming via microcontroller boards is becoming more effective and easier than before because several easy coding libraries support them, which saves time and effort when getting either analog or digital data from them. This book explains common sensor-programming libraries.

Who this book is for

This book is intended for students, hobbyists, geeks, and engineers alike who wish to dive into the world of microcontroller board programming. In addition, this book is suitable for digital electronics and microcontroller board beginners. If you are already a skilled electronics hobbyist and/or programmer, you may find this book helpful if you want to use and code efficient sensors with microcontroller boards.

People that use other types of microcontroller boards (such as Arduino boards) may find this book useful because it includes an introduction to the Blue Pill and Curiosity Nano microcontroller boards, facilitating the skills transfer required to understand and apply them in electronics projects requiring Arduino microcontroller boards.

Basic knowledge of digital circuits, and C and C++ programming language is desirable but not necessary. This is an introductory book on microcontroller boards for people who are starting with digital electronics projects.

What this book covers

This book covers technical topics on the programming of the Blue Pill and Curiosity Nano microcontroller boards using C++, including descriptions of commonly used sensors and how they are electronically connected to the microcontroller boards. The book consists of 14 chapters, as follows:

Chapter 1, Introduction to Microcontrollers and Microcontroller Boards, introduces the reader to microcontroller technology and explains how to install the integrated development environments (IDEs) necessary for programming the Blue Pill and Curiosity Nano microcontroller boards that are used in the book.

Chapter 2, Software Setup and C Programming for Microcontroller Boards, provides an overview of C and an introduction to Blue Pill and Curiosity Nano microcontroller board programming, which are used for coding examples in most of the book chapters.

Chapter 3, Turning an LED On or Off Using a Push Button, explains how to use push buttons with microcontroller boards to start a process, such as turning an LED on or off, and how electrical noise from a push button can be minimized.

Chapter 4, Measuring the Amount of Light with a Photoresistor, focuses on how to connect a photoresistor to the Blue Pill and Curiosity Nano microcontroller boards to measure the amount of light within an environment. The result is shown on red, green, and blue LEDs also connected to those boards.

Chapter 5, Humidity and Temperature Measurement, describes how to connect a practical DHT11 sensor to measure the humidity and temperature of an environment, how to display its values on a computer, and also how to use the easy-to-use LM35 temperature sensor, showing its values on two LEDs.

Chapter 6, Morse Code SOS Visual Alarm with a Bright LED, shows how to code the Blue Pill and Curiosity Nano microcontroller boards to display a Morse code SOS signal using a high-intensity LED, increasing its visibility. This chapter also explains how to use a transistor as a switch to increase the LED's brightness.

Chapter 7, Creating a Clap Switch, describes to the reader how to make an electronic wireless control using sounds (claps). When two claps are detected by a microphone connected to a microcontroller board, a signal will be transmitted to activate a device connected to it and an LED will light up.

Chapter 8, Gas Sensor, introduces the reader to the use of a sensor connected to a microcontroller board that reacts with the presence of a specific gas in an environment.

Chapter 9, IoT Temperature-Logging System, shows the reader how to build an Internet of Things (IoT) temperature logger using the Blue Pill microcontroller board and a temperature sensor. Its data will be transmitted via Wi-Fi using an ESP8266 module.

Chapter 10, IoT Plant Pot Moisture Sensor, explains how to build a digital device with a microcontroller board and a moisture sensor to monitor a plant pot's soil and determine if it needs water, sending an alert wirelessly to notify the user if it's too dry.

Chapter 11, IoT Solar Energy (Voltage) Measurement, continues applying IoT software running on a microcontroller board using the ESP8266 WiFi module to measure voltage obtained from a solar panel through a sensor. The application will send sensor data to the internet using the ESP8266 WiFi signal.

Chapter 12, COVID-19 Digital Body Temperature Measurement (Thermometer), looks at an interesting project to develop a contactless thermometer using an infrared temperature sensor. Its measured temperature data is sent through the I2C protocol to a Blue Pill microcontroller board, displaying it on an I2C LCD.

Chapter 13, COVID-19 Social Distancing Alert, explains how to program a microcontroller board that measures a distance of two meters between two or more people. Within the new normal of COVID-19, we need to maintain social distance due to the higher risk of catching the virus if you are close to someone who is infected. The World Health Organization recommends keeping a distance of at least two meters; this rule varies depending on the country, but it is generally accepted that a distance of two meters is safe.

Chapter 14, COVID-19 20-Second Hand Washing Timer, contains a practical project to make a timer running on a Blue Pill microcontroller board that ensures that people wash their hands for twenty seconds, as per World Health Organization recommendations, to prevent COVID-19 infection. This project shows the time count on a liquid-crystal display (LCD). An ultrasonic sensor detects if the user is waving at it to initiate the count.

To get the most out of this book

In order to use this book to the full, the reader will need basic knowledge of computer programming and the major operating systems (such as Windows or macOS), although there is a chapter that contains an introduction to C. In order to compile and run the programming examples described in this book, the reader should have the latest Arduino IDE previously installed on their computer (the Blue Pill board can be programmed using the Arduino IDE) and the MPLAB X IDE used for programming the Curiosity Nano microcontroller board; one of the chapters explains how to install and use them. All the program examples contained in this book for the Blue Pill microcontroller board should run on Windows, macOS, and Linux operating systems. The programs that run for the Curiosity Nano microcontroller board were tested on computers running both Windows and Linux operating systems.

If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Some pre-requisites for this book include having basic knowledge of computer programming and electronics, and having some materials, such as a solderless breadboard, many DuPont wires, LEDs, and resistors.

After reading this book, you can continue experimenting with the sensors used in the chapters and perhaps programming and applying other sensors to be connected to microcontroller boards, since this book provides a solid foundation for microcontroller boards programming and use.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/DIY-Microcontroller-Projects-for-Hobbyists. In case there is an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Code in Action

Code in Action videos for this book can be viewed at https://bit.ly/3cZJHQ5.

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781800564138_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

html, body, #map {

height: 100%;

margin: 0;

padding: 0

}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

[default]

exten => s,1,Dial(Zap/1|30)

exten => s,2,Voicemail(u100)

exten => s,102,Voicemail(b100)

exten => i,1,Voicemail(s0)

Any command-line input or output is written as follows:

$ mkdir css

$ cd css

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you've read DIY Microcontroller Projects for Hobbyists, we'd love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.

Chapter 1: Introduction to Microcontrollers and Microcontroller Boards

In this chapter, you will learn how to set up fundamental software tools for programming microcontrollers, as well as how to use basic electronic components as a starting point for programming examples for beginners. We will begin with a general introduction to microcontrollers and their definitions, as well as their importance and applications in our everyday lives. We will then go on to give a simplified explanation of the digital and analog electronics necessary for the microcontroller projects carried out in the rest of the chapters. Here, we will also explain the basic equipment that may be used in this book's projects. Finally, we will look at a concise description of the Blue PillandCuriosity Nano microcontroller boards to be used throughout this book.

Specifically, we will cover the following main topics:

Introduction to microcontrollersAn overview of analog and digital electronics necessary for carrying out the book's projectsDescription of the Blue Pill and Curiosity Nano microcontroller boards

We will also cover how to install the necessary software drivers and the integrated development environments (IDEs) for programming the Blue Pill and Curiosity Nano. After completing this introductory chapter, you will be able to apply what you have learned regarding the installation of integrated development environments (a type of software tool) to programming the obligatory Hello World programs used to make an LED blink. This will run on the Blue Pill and Curiosity Nano using C. Don't worry if you don't know a lot about C programming yet; we have you covered; Chapter 2, Software Setup and C Programming for Microcontroller Boards, includes a gentle but concise C programming tutorial.

Technical requirements

The two microcontroller boards described in this book (Blue Pill and Curiosity Nano) can be programmed using different IDEs. An IDE is a programming and debugging software tool that includes a code editor, a compiling environment, debugging options, and so on. Many of the IDEs are also used to upload your compiled program to a microcontroller board via a USB port connection.

These are the IDEs that you will need to install on your computer:

Arduino IDE: This free IDE was originally created for programming Arduino microcontroller boards, but you can also use it for programming the Blue Pill microcontroller board if you install a library for it.MPLAB ® X IDE: Made by Microchip, the Curiosity Nano manufacturer. This is a free IDE necessary for programming the Curiosity Nano.

We will explain how to install and use those IDEs in this chapter.

The code used in this chapter can be found at the book's GitHub repository here:

https://github.com/PacktPublishing/DIY-Microcontroller-Projects-for-Hobbyists/tree/master/Chapter01

The Code in Action video for this chapter can be found here: https://bit.ly/3zSOg8O

For hardware, you will need the following materials:

A regular LED light – any color will do.A 220-ohm resistor; 0.25 watts.A solderless breadboard for connecting an LED and a resistor and some male-to-male jumper wires to make the electrical connections between the components and the microcontroller boards.A micro USB cable for connecting your microcontroller boards to a computer.The Blue Pill and Curiosity Nano boards, of course! There are several vendors and manufacturers of the Blue Pill board, which uses the STM32F103C8T6 microcontroller. In the case of the Curiosity Nano, we use a version called the PIC16F15376 Curiosity Nano PIC® MCU 8-Bit Embedded Evaluation Board, part number DM164148, manufactured by Microchip. A programming adapter such as the ST-Link/V2 is also needed. This electronic interface will allow you to upload the compiled code to the Blue Pill, establishing communication from your computer to the Blue Pill microcontroller board. The ST-Link/V2 needs four female-to-female DuPont wires.

Some of the sensors used in this book can be found in a sensor kit in the form of practical modules, such as the Kumantech 37-in-1 sensor kit:

http://www.kumantech.com/kuman-new-version-37-sensor-module-robot-project-starter-kit-for-arduino-r3-mega2560-mega328-nano-uno-raspberry-pi-rpi-3-2-model-b-b-k5_p0017.html.

This kit can be used with many types of microcontroller boards, including the Blue Pill and the Curiosity Nano. Sometimes, it is convenient to buy a sensor kit like this one for experimenting with its sensor modules. Some other kits include components such as resistors and code examples.

Introduction to microcontrollers

In this section, we will focus on what a microcontroller is and what its main parts are. It is important to understand what the microcontrollers are capable of and how they are used as a fundamental part of many embedded systems, so they can be used in real-world projects. An embedded system is a computer subsystem that usually works as part of a larger computer system, for example, a wireless router containing a microcontroller. Let's start with a definition of microcontrollers.

A microcontroller (also known as a microcontroller unit, or MCU) is a very small computer system self-contained in an integrated circuit (IC). It encases all the necessary computing components to execute tasks, computes numeric calculations, reads data from sensors, keeps data and a program in memory, and send data to actuators, among other actions. Most of the microcontrollers perform analog-to-digitalconversion (ADC), obtaining analog data from sensors and converting it to digital values. More on ADC is explained in Chapter 4, Measuring the Amount of Light with a Photoresistor. Digital values are defined by binary values (1 or 0). The next section explains more about those values.

Microcontrollers have an internal clock signal that is like a heartbeat that coordinates how tasks and other actions are performed in the microcontroller. This clock signal is not as fast as microprocessors (used by desktop computers and laptops), but it is enough for doing basic operations such as reading a sensor or controlling a motor. Their internal memory is limited, but enough for storing a program capable of running a particular task. In general, microcontrollers do not use an external data storage device such as a hard drive. Everything they need to run is encased in their IC.

An IC is an electronic circuit densely packaged in a small and flat piece of plastic. It contains many microscopic electronic components and electrically connected pins. ICs are manufactured in different packaging. Dual in-line packaging (DIL) houses two rows of electrically connecting pins. Quad flat packaging (QFP) includes 8–70 pins per side, useful for surface mounting soldering. Microcontrollers are encased in ICs, as well as other electronic parts.

The pins of some microcontrollers are organized into two rows using DIL packaging. Other ICs, such as the STM32 microcontroller, have four rows of pins, which is known as QFP.

Microcontrollers are also called a computer in a chip. They generally have low-power consumption, and, of course, are reduced in size. Some of them are smaller than a fingernail! Microcontrollers are generally used to perform a specific task and execute one particular application, such as controlling the internal functions of a coffee maker, one at a time. Microcontrollers are applied in situations where dedicated and limited computer functions are needed.

Microcontroller boards

A microcontroller board is an electronic circuit containing a microcontroller and other supporting components such as voltage dividers/shifters, a USB interface, connection pins, resistors, capacitors, and an external clock.

The purpose of microcontroller boards is to facilitate the connection of external devices, sensors, and actuators to microcontrollers, accelerating project prototyping. For example, the Blue Pill microcontroller board contains its microcontroller at its center, and it has some other components supporting its functions.

Microcontroller boards such as the Blue Pill have input/output (I/O) ports, or pins, where sensors, motors, and other electronic components and devices are connected to them. The boards will either read or send data to them through the ports. The boards also have useful pins such as the ground and voltage pins, so sensors and other components can be connected to them to work. Some I/O pins read analog voltages coming from sensors or send analog voltages to actuators (for example, motors), and others are digital pins used for reading and sending digital voltages, typically 0 and 5 volts, or 0 and 3.3 volts. All computers (including microcontrollers) work internally with digital binary numbers containing 0s and 1s. The binary value 0 is represented by 0 volts, and the binary value 1 is represented by either 3.3 or 5 volts. For example, a digital value (1) sent to a digital port could turn on an LED connected to it.

The next section defines what electronics is, and what are analog and digital electronics. These definitions are important in understanding how some electronic components and electronic circuits work, which will be used in this book's chapters.

An overview of analog and digital electronics necessary for carrying out the book's projects

Electronics is the branch of technology and physics concerning the emission and behavior of electrons moving in a conductor, semiconductor, gas, or vacuum. Electronics also deals with the design of electronic circuits and devices. Figure 1.1 shows a diagram of a basic electronic circuit consisting of a power source (the batteries), a resistor, and a light source (a light-emitting diode, or LED):

Figure 1.1 – An example of an electronic circuit

The electrons flow from the battery's negative (black) terminal through the circuit passing through the LED illuminating it. Don't worry if you don't understand this circuit and its components yet. We will review these in the next paragraphs, and we will use them in other chapters. Analog electronics are electronic circuits that provide and process continuous variable voltage signals, for example, analog voltages that change from 0 to 3.3 volts. Conversely, digital electronics provide and process discrete voltage signals that represent binary values. For example, 0 volts represents a 0 in binary, and 3.3 volts represents a 1 in binary, and no other voltages are used in between. This is how computers and microcontrollers work internally at the lowest level. Microcontrollers convert analog values to digital values internally in order to process incoming signals and then process them digitally. This is called analog-to-digital conversion (ADC). We will need to understand four key electronics terms that will be covered in other chapters, which are standard units used to measure the flow of electrons:

Current: Current is the rate of flow of electrons in a circuit. Electrons flow through a conductive material from the negative pole of a power source (such as a battery) to its positive pole. This is known as direct current (DC). The negative side is called ground (GND, or G), sometimes also called earth. Current is measured in amperes or amps, denoted by the letter I or i.Voltage: This is an electrical measurement of the difference in potential energy between the positive and negative poles of a power source in an electronic circuit. It is measured in volts (V). It is considered as the pressure from an electrical circuit's power source pushing charged electrons (current) through an electric/electronic circuit.Power: Power is a rate measurement of how an electric or electronic circuit or device converts energy from one form to another. Power is measured in watts (W). For example, a 60 W lightbulb is brighter than a 40 W lightbulb because the 60 W lightbulb converts electrical energy into light at a higher rate.Resistance: The electrical resistance of an electrical conductor is the measurement of the difficulty of the electrons in passing an electric current through the conductor. It is measured in ohms, denoted by the Greek letter Omega (Ω). Ohm's law describes the conductivity of many electrically conductive materials. It establishes that the current between two points in a conductor is directly proportional to the voltage across the two points, where its resistance is constant. This law can be mathematically described as I=V/R, and it is very useful for calculating either current, voltage, or resistance in an electronic circuit.

In this section, we have covered fundamental standard measurement units used in electronic circuits that you will apply in all the chapters of this book. The next section deals with important electronic components that you will also need to know before starting experimenting with electronic circuits and microcontroller boards.

Basic electronic components

The following are electronic components commonly used in many microcontroller board projects and in most of the projects described in this book. They allow us to control the current in electronic circuits. We will review four main electronic components: the resistor, the diode, the capacitor, and the transistor.

The resistor

Resistors are generally used to reduce the flow of electrons in an electronic circuit. Resistance is useful for allowing some components such as LEDs to work properly in a circuit without burning them. The level of resistance in a resistor can be either fixed or variable. Some resistors can range from one to thousands of ohms (kilo-ohms or kΩ) to millions of ohms (mega-ohms or MΩ). Resistors are also measured by their power rating measured in watts. This refers to how much current they tolerate without overheating and then failing.

Figure 1.2 shows how to read the values of a resistor:

Figure 1.2 – A chart showing how to calculate a resistor value. Image source: "Resistor Color Code", by Adim Kassn, licensed under CC-BY-SA-3.0

Important note

As shown in Figure 1.2, the band colors are:

0: Black

1: Brown

2: Red

3: Orange

4: Yellow

5: Green

6: Blue

7: Violet

8: Silver

9: White

The 1% tolerance band is colored brown, the 2% is colored red, the 5% is colored gold, and the 10% is colored silver. You can access the chart in color via this link: https://commons.wikimedia.org/wiki/File:Resistor_color_code.png.

Common resistors have four color bands (some have five color bands, but this is rarely used in general electronic circuits) determining their ohm values:

The first band indicates the first digit in its ohm value.The second band shows the second digit.The third band indicates the third digit (which is typically the number of zeros).The fourth band determines the resistor tolerance, which is a degree of resistance precision. For example, if the band is colored silver, this means that the resistor will have a 10% tolerance change according to its marked value.

Many resistors used in microcontroller board projects use ¼ watt resistors, which are enough for simple applications.

The diode

The diode is an electronic component that allows the flow of current in one direction only. Current in a circuit flows into a diode via its anode (+) and flows out through its cathode (-). Diodes are generally used to protect parts of an electronic circuit against reverse current flow. They also help to convert alternate current (AC) to DC, among other applications. Diodes are also used to protect microcontroller boards when we connect motors to them to avoid voltage flyback. This happens when a sudden voltage spike happens across a motor when its supply current is suddenly interrupted or reduced. However, diodes cause a drop in the voltage of around 0.7 V. Diodes are manufactured to handle a certain amount of amperes (current) and voltage. For example, the 1N4004 diode is rated to handle 1 ampere (A) and 400 volts (V), much higher than we will be using in our book's projects. The band around the diode indicates the cathode, generally connected to the ground terminal of a power source. The other pin is the anode, generally connected to the positive (+) terminal of the power source. A common type of diode is the light-emitting diode (LED), which glows when there is a flow of electrons passing through it. They come in different sizes, colors, and shapes. As with regular diodes, LEDs are polarized, so the current enters and leaves the LED in one direction. If too much current passes through the LED, this will damage it. You will need to connect a resistor in series to reduce its current and thus protect it. A resistor with a value of at least 220 ohms should be enough for many microcontroller board applications.

The capacitor

This is an electronic component that temporarily holds (stores) an electric charge. Once the current stops flowing through the capacitor, the charge remains in it and it can be discharged as soon as the capacitor is connected to a circuit. The amount of charge that a capacitor can store is measured in farads (f). Since a farad is a very large amount, many capacitors are made with less than one farad. Capacitors accept certain voltage maximums. 10, 16, 25, and 50 V capacitors are common in microcontroller applications. There are two types: monolithic (they don't have polarity) and electrolytic (they have polarity).

Electrolytic capacitors are bigger than monolithic capacitors, and their polarity is shown as a band on one side marking the cathode pin and another band marking the anode pin. Remember that the cathode pin is connected to the ground terminal of the power source and the anode is connected to the positive voltage terminal of the power source. Typical values of electrolytic capacitors range from 1 microfarad up to 47,000 microfarads. Capacitors can be used in microcontroller board projects for filtering out (cleaning up) digital or analog signals (removing electrical noise), they can convert alternate voltage to direct voltage, and so on. Be very careful when you're using polarized (electrolytic) capacitors! They can hold lots of energy. You should never touch its legs (pins), short circuit, or connect them in reverse. Make sure you connect an electrolytic capacitor in a project by connecting its positive (+) pin to the positive pole of the circuit's power supply (an electronic/electric component that supplies steady power to an electronic circuit or electrical device) and by connecting the capacitor's negative pin to the negative pole of the circuit's power supply. Respect its polarity. If you connect them in reverse (wrong polarity), they will be damaged and can explode. Monolithic (ceramic) capacitors do not have polarity. It doesn't matter how their legs (pins) are connected in the circuit. The typical capacity range of capacitors is from 0.5 picofarads up to 1 microfarad.

The transistor

A transistor can act as a very fast digital switch. Transistors are useful for switching on or off other circuits or devices that require a high current, such as motors and fans. It can also be used as a current amplifier and to form logic gates (AND, OR, NOT, and so on); this current is also called a load. Popular and inexpensive examples are the BC548 and 2N2222 transistors. Transistors