Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
DIY Microcontroller Projects for Hobbyists

You're reading from   DIY Microcontroller Projects for Hobbyists The ultimate project-based guide to building real-world embedded applications in C and C++ programming

Arrow left icon
Product type Paperback
Published in Jul 2021
Publisher Packt
ISBN-13 9781800564138
Length 320 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Miguel Angel Garcia-Ruiz Miguel Angel Garcia-Ruiz
Author Profile Icon Miguel Angel Garcia-Ruiz
Miguel Angel Garcia-Ruiz
Pedro Cesar Santana Mancilla Pedro Cesar Santana Mancilla
Author Profile Icon Pedro Cesar Santana Mancilla
Pedro Cesar Santana Mancilla
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Chapter 1: Introduction to Microcontrollers and Microcontroller Boards 2. Chapter 2: Software Setup and C Programming for Microcontroller Boards FREE CHAPTER 3. Chapter 3: Turning an LED On or Off Using a Push Button 4. Chapter 4: Measuring the Amount of Light with a Photoresistor 5. Chapter 5: Humidity and Temperature Measurement 6. Chapter 6: Morse Code SOS Visual Alarm with a Bright LED 7. Chapter 7: Creating a Clap Switch 8. Chapter 8: Gas Sensor 9. Chapter 9: IoT Temperature-Logging System 10. Chapter 10: IoT Plant Pot Moisture Sensor 11. Chapter 11: IoT Solar Energy (Voltage) Measurement 12. Chapter 12: COVID-19 Digital Body Temperature Measurement (Thermometer) 13. Chapter 13: COVID-19 Social-Distancing Alert 14. Chapter 14: COVID-19 20-Second Hand Washing Timer 15. Other Books You May Enjoy

Introducing the C programming language

The C programming language was initially created in the early seventies for developing the UNIX operating system, but it has been ported to practically all operating systems ever since. It is a mid-level programming language because it shares properties from high-level languages such as Python and low-level languages, for example, the assembly language. The C language is generally easier to program than low-level languages because it is very human-readable and there are many libraries available that facilitate the development of software applications, among other reasons. It is also very efficient for programming embedded systems. C is one of the most popular coding languages, and virtually all microcontrollers can be programmed with C compilers – Blue Pill and Curiosity Nano are no exceptions.

The C language is not completely portable among different families and manufacturers of microcontrollers. For example, the I/O ports and the interrupts are not programmed the same in both Blue Pill and Curiosity Nano. That is why two types of C compilers and different libraries are needed for programming both microcontroller boards. In fact, the Arduino IDE used for programming the Blue Pill uses a variant of C called C++. C++ is a powerful extension of the C programming language that incorporates features such as object-oriented and low-memory level programming.

The following section explains the basics of the C language structure. This section includes an explanation of the #include directive, writing comments, understanding variables, using constants, a keywords list, declaring functions, evaluating expressions, and writing loops in C.

The basic structure of the C language

As with other programming languages, C makes it possible to declare program elements such as constants, types, functions, and variables in separate files called header files, which end in .h. This can help to organize C instructions and reduce clutter in your main C code. A library is a header file containing program elements (such as functions) that can be shared with other C programmers or constantly used in different C programs. C language compilers contain important libraries that we will use in this book. The header files can be included (that is, linked and compiled) along your main program using the #include directive; hence, the programming elements declared in the header file will be called and used in your C program.

There are many useful standard and non-standard libraries. We will review and use both. The #include directive is a special instruction for the C compiler and not a regular C instruction. It should be written at the beginning of the program and without a semicolon at the end. Only the C statements have a semicolon at the end. There are three ways to write and apply the #include directive. These are as follows:

  • #include <file_name.h>: This type of directive uses the less than and greater than symbols, meaning that the header file (.h) is placed in the compiler path. You don't need to write the complete path to the header file.
  • #include "file_name.h": This type of directive uses double quotes. The header file is stored in the project's directory.
  • #include "sub_directory_name/file_name.h": This directive type tells the compiler that the header file is placed in a sub-directory. Please note that the slash symbol is applied depending on the operating system that you are using. For example, Windows computers use a backslash (\) symbol as a directory separator. Linux and Mac computers use the forward-slash (/) symbol.

The next sub-section shows how to define and use header files.

Example of the #include directive

The following program example shows how to include a header file that is placed in the project's directory:

#include "main_file.h"
int main(void)
{
    x = 1;
    y = 2;
    z = x+y;
}

In the preceding example, the x, y, and z variables were declared in the main_file.h header file, so they are not declared in the main program. The header file (file.h) contains the following code declaring the three variables used in the main code:

int x;
int y;
int z;

We could declare the variables in the main program and not declare the variables in a header file (.h). It is up to you whether you want to write program elements in header files. We will learn more about variables later in this chapter.

Note

The C language is case sensitive, so be careful when writing C code. Most C language instructions are written in non-capitalized letters. Be careful when you declare a variable, too. For example, the variables x and X are different in C.

There are standard libraries that come with the C language and many programmers make good use of them. The stdio.h library (stored as a header file) is widely used in C programming. It defines several macros, variable types, and also specialized functions for performing data input and output; for example, taking input letters from a keyboard or writing text to the console. The console is a text-based area provided by the IDE where reading data from a keyboard or writing text or special characters happens.

This is a short C program example using the <stdio.h> directive:

// program file name: helloworld.c
#include <stdio.h>  
int main()  
{  // start main block of instructions
     printf("Hello world!"); 
     return 0;
} 

C program files are stored with the .c extension (such as mainprogram.c). The C++ program files are generally stored with the .cpp extension (for example, mainprogram.cpp).

The American National Standards Institute (ANSI) C language defines a number of useful built-in functions, such as printf(), which displays characters (for example, a text message) on the IDE's console. As you can see from the preceding program example, we wrote some comments explaining each line of code. The next section shows the different ways of writing comments in the C language.

Using comments in C

Comments are either blocks or lines of text that don't affect the functioning of C programs. Writing comments in C programming is useful because they can be used to explain and clarify the meaning or the functioning of instructions, functions, variables, and so on. All the comments that we write in the program are ignored by the compiler. There are a couple of ways of writing comments in C:

  • Using double slashes (//): This makes a single-line comment.
  • Using slashes and asterisks (/*  */): This makes a comment with a block of text.

This code example demonstrates how to use both types of comments:

/**********************************************************
Program: Helloworld.c 
Purpose: It shows the text "Hello, world!!" on the IDE's console. 
Author: M. Garcia.
Program creation date: September 9, 2020.
Program version: 1.0 
**********************************************************/
#include <stdio.h>  //standard I/O library
int main(void)
{
    int x; // we declare an integer variable
                  
    printf("Hello, world!!"); 
    x=1; // we assign the value of 1 to variable x.
}

Tip

It is a good programming practice to write the code's purpose, version number and date, and the author's name(s) as comments at the beginning of your C program.

The next section describes how to declare and use variables in C programming. Variables are very useful, and you will use them in most of the chapters of this book.

Understanding variables in C

A variable is a name (also called an identifier) assigned via programming to a microcontroller memory storage area that holds data temporarily. There are specific types of variables in C that hold different types of data. The variable types determine the layout and size of the variable's assigned microcontroller memory (generally, its internal random-access memory or RAM).

We must declare a variable in the C language first to use it in your code. The variable declaration has two parts – a data type and an identifier, using this syntax: <data_type> <identifier>. The following explains both:

  • A data type (or just type) defines the type of data to be stored in the variable (for example, an integer number). There are many data types and their modifiers. The following table describes the four main types:
Table 2.1 – The main four data types used in the C language

Table 2.1 – The main four data types used in the C language

  • Each type from Table 2.1 has the modifiers unsigned, signed, short, and long, among others. For example, we can declare a variable that holds unsigned integers as unsigned int x;.
  • There is another type named void. This type has no value and is generally used to define a function type that returns nothing.
  • An identifier is a unique name identifying the variable. Identifiers can be written with the letters a..z or A..Z, the numbers 0..9, and the underscore character: _. The identifier must not have spaces, and the first character must not be a number. Remember that identifiers are case-sensitive. In addition, an identifier should have fewer than 32 characters according to the ANSI C standard.

For example, let's declare a variable named x that can hold a floating-point number:

float x;

In the preceding line of code example, the C compiler will assign variable x a particular memory allocation holding only floating-point numbers.

Now, let's use that variable in the following line of code:

x=1.10;

As you can see, we store the floating-point value of 1.10 in the variable named x. The following example demonstrates how to use a variable in a C program:

/* program that converts from Fahrenheit degrees to Celsius degrees. Written by Miguel Garcia-Ruiz. Version 1.0. Date: Sept. 9, 2020
*/
#include <stdio.h> // standard I/O library to write text
int main(void) // It won't return any value
{
    float celsius_degrees;
    float fahrenheit_degrees=75.0;
    // Calculate the conversion:
    celsius_degrees=(fahrenheit_degrees-32)*5/9;
    // printf displays the result on the console:
    printf("%f",celsius_degrees); 
}

You can initialize a variable with a value when it is declared, as shown in the preceding example for the fahrenheit_degrees variable.

We can also store strings in a variable using double quotes at the beginning and end of the string. Here's an example:

char  name = "Michael";

The preceding example shows how a string is stored in a char variable type, which is an array of characters.

Declaring local and global variables

There are two types of variables in C depending on where they are declared. They can have different values and purposes:

  • Global variables: These are declared outside all the functions from your code. These variables can be used in any function and through the whole program.
  • Local variables: Local variables are declared inside a function. They only work inside the function that were declared, so their value cannot be used outside that function. Have a look at this example containing both global and local variables:
#include<stdio.h>
// These are global variables:
int y;
int m;
int x;
int b;
int straight_line_equation() {
    y=m*x+b;
    return y;
}
int main(){
    int answer;  // this is a local variable
    m=2;
    x=3;
    b=5;
    answer = straight_line_equation();
    printf(" %d\n  ",answer);
    return 0;  // this terminates  program
}

In the preceding example, the global variables y, m, x, and b work in all programs, including inside the straight_line_equation() function.

Using constants

Constants (also called constant variables) can be used to define a variable that has a value that does not change throughout the entire program. Constants in C are useful for defining mathematical constants. This is the syntax for declaring a constant:

const <data_type> <identifier>=<value>;

Here, the data type can be either int, float, char, or double, or their modifiers, for example:

const float euler_constant=2.7183;
const char A_character='a';

You can also declare variables using the #define directive. It is written at the beginning of a program, right after the #include directive, without a semicolon at the end of the line, using this syntax: #define <identifier> <value> .

We don't need to declare the constant's data type. The compiler will determine that dynamically. The following examples show how to declare constants:

#define PI 3.1416
#define value1 11
#define char_Val 'z'

The next section deals with keywords from the C language that are widely used in C programs.

Applying keywords

The ANSI C standard defines a number of keywords that have a specific purpose in 
C programming. These keywords cannot be used to name variables or constants. These are the keywords (statements) that you can use in your C code:

auto, break, case, char, const, continue, default, do, double, else,  enum, extern, float, for, goto, if, int, long, register, return, short, signed sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while.

The compilers used to compile programs for the Blue Pill and Curiosity Nano boards have additional keywords. We will list them in this chapter. The following section explains what functions in C are.

Declaring functions in C

A function is a block that contains a group of C instructions, or just a single instruction, that will perform a task, or a number of tasks, with a particular purpose. The block of instructions is encompassed with curly brackets. A C program has at least one function, which is main(). This function is written in C programs, and other functions are called from it. You can logically divide your code up into functions to make it more readable and to group instructions that are related to the same task, giving the instructions some structure. Functions in C are defined more or less like algebraic functions where you have a function name, a function definition, and a function parameter(s).

The general form for defining a function in C is the following:

<return_data_type> <function_name> (parameter list) {    <list of instructions>
    return <expression>; //optional
}

The parameters (also called arguments) input data to a function. The parameters are optional since a function cannot have parameters at all. We need to declare the type of each parameter. The variables declared as parameters behave like local variables for the function where they were declared. The variables declared as parameters are also called the function's formal parameters, and these are also termed call by value, meaning that the changes made to the parameters (the variables) inside their function do not have any effect on them. In other words, the instructions from inside a function cannot alter the values of its function's parameters. The return statement allows a value from a function to be returned, and this returned value is used in other parts of the program. The return statement is optional since you can code a function that does not return a value.

Tip

It is a good programming practice to indent the instructions contained in a function block. This gives the function more visual structure and readability.

The following function example shows how to use parameters and how data is returned from a function, where number1 and number2 are the function parameters:

int maxnumber(int number1, int number2) {
    /* Declaring a local variable to store the result: */
    int result1;
    if (number1 > number2)
        result1 = number1;
    else
        result1 = number2;
    return result1; 
}

In the preceding example, the function returns the results of the comparison between the two numbers.

Tip

Make sure that the function's data type has the same type as the variable used in the return statement.

If, for some reason, you don't need to return a value from a function, you can use the void statement instead of defining the function's data type, for example:

void error_message ()
{
    printf("Error.");
}

In the preceding example, we are not using the return 0 statement in the function because it's not returning any value. We can then call the function by its name: error_message();.

Calling a function

Once we declare a function, we need to call it, that is, run it in another part of your code. This transfers the program control to the called function and it will run the instruction(s) contained in it. After executing all the instructions from the function, the program control resumes, running instructions from the main program.

To call a function, you will need to write the function name and the required values for the parameters. If your function returns a value, you can store it in a variable. For example, let's call the max() function that we explained previously:

int result2;
result2=maxnumber(4,3);

In this example, the result of the number comparison made by the maxnumber() function will be stored in the result2 variable.

Evaluating expressions (decision statements)

The C language provides a way to declare one or more logic conditions that can be evaluated (tested) by the program, as well as some statements that need to be executed according to the result of that evaluation, that is, if the condition is either true or false.

The C programming language assumes that the true value is any non-null or non-zero value. It is false if the value is zero or null. C has the following decision-making statements:

  • if (expression_to_evaluate) {statements}: This has a Boolean expression in the decision that is followed by one or more statements to be run if the decision is true, for example:
    #include <stdio.h>
    void main(){
    	int x;
    	x=11;
    	if (x>10) {
    		printf("yes, x is greater than 10");
    	}
    }
  • if (decision) {statements} else {statements}: The else component can be used after an if statement and can be useful when running one or more statements if the decision is false, for example:
    #include <stdio.h>
    void main(){
      int x;
      x=5;
      if (x>10) {
         printf("yes, x is greater than 10");
      }
      else {
        printf("no, x is not greater than 10");
      }
    }

    In the preceding example, the x variable is analyzed, and if x is greater than 10, it will print out this message on the IDE's console: yes, x is greater than 10, otherwise it will print out no, x is not greater than 10.

    Tip

    Be careful when you evaluate two variables with the if statement. Use double equal signs for that (==). If you use only one equal sign, the compiler will raise an error. Do it like this: if (x==y) {statements}

  • The switch statement compares the value of a variable against a number of possible values, which are called cases. Each case from the switch statement has a unique name (identifier). If a match is not found in the list of cases, then the default statement will be executed and the program control goes out of the switch with the list of cases. The optional break statement is used to terminate the program control outside of the switch block. This is useful if, for some reason, you don't want the switch statement to keep evaluating the rest of the cases. The following is the syntax for the switch statement:
switch( expression_to_evaluate)
{
    case value1:
        <statement(s)>;
        break;
    case value_n:
        <statement(s)>;
        break;
}

The preceding code shows the syntax for the switch statement, including its break sentence. The following code is an example of using switch, which will compare the variable age against three cases. In case the variable has a value of 10, it will print out the following text: the person is a child:

#include <stdio.h>
void main(){
	int age;
	age=10;
	switch (age)
	{
		case 10:
			printf ("the person is a child");
			break;
		case 30:
			printf ("the person is an adult");
			break;
		case 80:
			printf ("the person is a senior citizen");
			break;
	}	
}

So far, we have reviewed how to logically evaluate an expression. The next section explains how to run one or more statements repeatedly. This can be useful for some repetitive tasks for the microcontroller board, such as reading data from an input microcontroller port continuously.

Understanding loops

A loop in C executes a single line of code or a block of lines of code a number of times, and if programmed, it could run endlessly. The C programming language provides three ways of making loops using the keywords for, while, and do..while:

for loop

The for loop repeats one or more statements contained in its block until a test expression becomes false. This is the syntax of the for loop:

for (<initialization_variable>;         <test_expression_with_variable>; <update_variable>)
{
    <statement(s)_to_run>;
} 

In the preceding syntax, the counter_variable initialization is executed once. Then, the expression is evaluated with counter_variable. If the tested expression is false, the loop is terminated. If the evaluated expression is true, the block statement(s) are executed, and counter_variable is updated. counter_variable is a local variable that only works in the for loop. This example prints out a list of numbers from 1 to 10 on the IDE's console:

for (int x=1; x<=10; x++)
{
    printf("%d ", x);
}

Please note that the x++ statement is the same as writing x=x+1.

while loop

The while loop repeats one or more statements from its block while a given condition is true, testing its condition prior to executing the statements. When its condition tests false, the loop terminates. Here is the syntax for the while loop statement:

while (<test_expression>) 
{
    statement(s); 
}

The preceding code is the syntax for the while loop. The following is example code that uses the while loop, counting from 0 to 10:

int x = 0;
while (x <= 10)
{
    // \n it will display the next number in a new 
    // line of text:
    printf("%d \n", x); 
    x=x+1;
}

do..while loop:

This type of loop is very similar to the while loop. The do..while loop executes its block statement(s) at least once. The expression is evaluated at the end of the block. The process continues until the evaluated expression is false.

The following is the syntax for the do..while loop:

do
{
    statement(s);
}
while (<test_expression>);

The following example uses the do..while loop, counting numbers from 5 to 50, while the sum is < 50:

int number=5;
do
{
    number=number+5;
    printf("%d ", number);
}
while (number < 50);

In the preceding code, the variable called number has the value 5 added to it and the variable is printed out on the IDE's console at least once, and then the variable is evaluated.

The infinite loops

You can also program an infinite loop, which, of course, will run endlessly (the loop does not terminate) until we abort the program (or disconnect the power from the microcontroller board!). Infinite loops can be useful for showing a result from a microcontroller continuously, reading data from a microcontroller board continuously without stopping it, and so on.

You can do this using any of the three types of loops. The following are some examples of infinite loops:

for(; ;)
{
    printf("this text will be displayed endlessly!");
}
while(1) 
{
    printf("this text will be displayed endlessly!");
}
do
{
    printf("this text will be displayed endlessly!");
}
while (1);

As you can see from the preceding code, programming endless loops is easy and simple.

The break and continue keywords in loops

You can break running a block of statements from a loop using the break keyword. The break statement of the following example will stop the for loop, but the statement will run only once:

for (int x=1; x<=10; x++)
{
    printf("%d ", x);
    break;
}

You can use the break statement in any of the three types of loops.

The continue keyword will force the next iteration of the loop to run, skipping any statement written after the continue keyword. This example will not print out the second line of text:

for (int x=1; x<=10; x++)
{
    printf("%d ", x);
    continue;
    printf("this line won't be displayed.");
}

The preceding code displays the value of x without displaying the next line of text because of the continue statement, moving the program control to the beginning of the for loop.

The next section deals with a number of C statements and functions that were created specifically for the Curiosity Nano microcontroller board and that are slightly different from those for the Blue Pill board.

You have been reading a chapter from
DIY Microcontroller Projects for Hobbyists
Published in: Jul 2021
Publisher: Packt
ISBN-13: 9781800564138
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image