Book Image

DIY Microcontroller Projects for Hobbyists

By : Miguel Angel Garcia-Ruiz, Pedro Cesar Santana Mancilla
Book Image

DIY Microcontroller Projects for Hobbyists

By: Miguel Angel Garcia-Ruiz, Pedro Cesar Santana Mancilla

Overview of this book

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.
Table of Contents (16 chapters)

Writing a program for getting data from the ultrasonic sensor

In this section, you will learn how to write a program to gather data from the ultrasonic sensor. Let's start, as follows:

  1. First, we will define which pins of the STM32 Blue Pill card will be used to read the sensor data. Also, we will declare two variables to save the duration of the sound-wave travel and another for calculating the distance traveled, as illustrated in the following code snippet:
    const int pinTrigger = PC14;
    const int pinEcho = PC13;
    long soundWaveTime;
    long distanceMeasurement;

    The selected pins were the PC13 and PC14 pins (labeled C13 and C14 on the Blue Pill).

  2. Next, in the setup() function, begin the serial communication. You will set the trigger pin as an output pin and the echo pin as an input pin. We need to initialize the trigger in the LOW value. The code is illustrated in the following snippet:
    void setup() {
      Serial.begin(9600);
      pinMode(pinTrigger, OUTPUT...