MCAPP Lab 01 (Student) C Programming Fundamentals (Apr 25)
MCAPP Lab 01 (Student) C Programming Fundamentals (Apr 25)
Diploma in CEN
Diploma in ELN
Name: Class:
Objectives:
1. To learn basic C programming
Introduction
In this subject, we will be using the C language to program the microcontroller. In this lab,
you will learn the basics of C programming. The basics of C will be taught through a
series of code examples.
2 C Program Outline 4
3 Data Types 8
4 Identifiers 12
5 Operators 14
6 Decision Making 17
6.1 The if statement 17
6.2 The if, else statement 18
6.3 The if, else-if statement 19
7 Looping 20
7.1 The for loop 20
7.2 The while loop 21
8 Arrays 23
9 Functions 26
10 Summary Quiz 30
11 Lab 1 Extra 31
11.1 Use of Functions 31
11.2 Number System Conversion 33
Appendix A: C Keywords 35
A compiler is a program that translates a C program into its executable machine code in
binary format.
The compiler also ensures the program is syntactically correct (written according to the
rules of the programming language).
A different hardware (or machine) will support a different machine code format. For
example, the machine code format that runs in the Intel or AMD hardware which are used
to power our laptops is different from the machine code format of a microcontroller or
microprocessor used in our smart phones.
In other words, each computer or machine only understands its own machine code.
Hence, the program must be "translated" to its corresponding machine code by using the
compiler provider by the microcontroller company.
A simple C program is shown below. This simple program does a simple print to the
console. Go through the different parts of the program.
Exercise 2.1
In your laptop, go to the following webpage which contains an online C compiler:
https://www.programiz.com/c-programming/online-compiler/
Enter the program in Figure 2-1. Click Run to run the program.
The result will be display in the Output box on the right as shown below in Figure 2-2.
• Line 1:
// Online C compiler to run C program online
At the beginning of a program, comments are usually written to inform the reader what
this program does. The compiler ignores comments during compiling.
• Line 2:
#include <stdio.h>
Positioned at the beginning of a program, the line, #include <stdio.h> informs the
compiler to include the standard input/output library header file, stdio.h.
A header file (one with the extension .h) is where you can place shared constants or
declarations of functions.
The stdio.h header file contains the declarations for the printf() and scanf()
functions.
The printf() function is an output process (to a display) while scanf() function is an
input process (from the keyboard).
There are other preprocessor directives, such as #define which you will encounter in
this subject later and will be widely used in microcontroller programming.
Every C program must have one and only one main() function.
Match
9 return 0; (integer), the return
10 } value must be an
integer value.
Return value
Notice that the function main() is defined with the return type of int (integer). This
means that at the end of the function at line 9, an integer value must be returned out
of the function. In this case, a value of 0 is being returned.
In programming, zero is usually used to indicate a status that there are no errors when
the function is being run. A non-zero returned value indicates a specifc error.
Line 5 is an open-brace character, {. This character is used to indicate the start of the
block of statements within this function. Similarly, in line 10, the close-brace character,
} is used to indicate the end of the block of statements within this function.
This brace pair { } is also used in the for-loop and if-statement, which you will see
later.
return 0;
}
In line 7, the printf() function is called to display a text message on the console. Notice
that double quotes (" ") are used to enclose the string to be printed.
Notice too that this statement is terminated with the semicolon, which all C statements
are (except for C constructs such as if, which you will see later).
Answer:
Before we can make use of the printf() function at line 7, it is necessary to declare
it first.
By including the header file stdio.h, we are actually substituting it with the
declaration of printf().
In C, data types are declarations for variables. This determines the type and size of data
stored in the variables. In Table 3-1, you will see the different data types (not exhaustive)
as defined in the XC8 compiler. This compiler is the one that we will use to compile our
programs for the microcontroller.
char
-128 0 127
unsigned char
0 255
Variables that are declared with the first type can hold a value from -128 to 127, while
variables declared with the second type can hold a value from 0 to 255.
You can think of the word, unsigned as meaning not having a negative value.
How do we read the ASCII table? For example, the character '6' has the integer
value of 54, while the character 'h' has the integer value of 104.
When a machine wants to transmit the character 'h' to another machine, it will
transmit the encoded value of 104.
You can think of the data type, char as being "invented" in programming because
1-byte is sufficient to represent the entire 127 numeric codes in the ASCII "character"
table.
char fridgeTemp;
char gender;
unsigned char seconds;
fridgeTemp = -1;
gender = 'm';
seconds = 0;
Example 3: Declaring variables and initialising values to them at the same time
Study the 3 examples above. In example 1, the variables are simply declared without
values assigned to them. In example 2, after the variables are declared, they are
each assigned with respective values. Finally in example 3, these variables are both
declared and initialised with respective values. Examples 2 and 3 illustrate valid and
possible methods of assigning the variables with values.
int
-32768 0 32767
unsigned int
0 65535
y_coord = -10;
daysInYear = 365;
• float
Finally, this data type is used to declare variables that needs to store a floating-point
value, e.g., 3.456.
Exercise 3.1
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 int main() {
4 char fridgeTemp = -1;
5 char gender = 'm';
6 unsigned int daysInYear = 365;
7 float radius = 3.456;
8
9 printf("Fridge temperature = %d\n", fridgeTemp);
10 printf("gender = '%c' (%d)\n", gender, gender);
11 printf("daysInYear = %d\n", daysInYear);
12 printf("radius = %.2f\n", radius);
13 return 0;
14 }
Question:
What is the effect of the format specifiers?
a) %c
b) %.2f
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
Identifier:
An Identifier refers to a name given to entities in C such as variables, arrays, and
constants. It is a sequence of letters and/or digits and must start with a letter. Identifiers
are case sensitive. For example, termA is different from TermA.
Variable:
We have seen earlier how a variable can be declared with a specific data type. Upon
being declared, it is allocated a memory location in the computer's memory to store its
value. Take for instance the statement below:
The variable, seconds is allocated a memory location in RAM to store the value of 0 as
shown in Figure 3-4.
RAM
0 Memory What
Locations happens in
seconds computer
variable is allocated a
memory?
memory location
Constant:
A constant’s value cannot be changed during the execution of a program. The #define
directive allows the programmer to use a symbolic name in place of a constant.
An example is the constant π used in calculation of perimeter or area of circles:
#define PI 3.142
• An identifier cannot be a keyword (reserved word). For examples, main, new, true,
false, null.
The #define directive should be placed just before main() in your program.
Exercise 4.1
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 #define PI 3.142
4
5 int main () {
6 float radius = 1.2, area;
7
8 area= PI * radius * radius;
9 printf("Given the radius %.1f,\n", radius);
10 printf("The area of circle is %.2f\n", area);
11 return 0;
12 }
Question:
Why would you not declare PI as a variable?
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
Exercise 5.1:
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 int main() {
4 int a = 9, b = 4, c;
5 float y = 4.0, z;
6
7 c = a/b;
8 printf("a/b = %d \n", c);
9
10 z = a/b;
11 printf("a/b = %.2f \n", z);
12
13 z = a/y;
14 printf("a/y = %.2f \n", z);
15
16 c = a%b;
17 printf("Remainder when a divided by b = %d \n", c);
18
19 return 0;
20 }
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
Exercise 5.2:
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 int main() {
4 int a = 9, b = 4, c, d;
5
6 a++;
7 printf("The incremented value of a is: %d \n", a);
8
9 b--;
10 printf("The decremented value of b is: %d \n", b);
11
12 c = 500;
13 printf("c = %d\n", c); Relational
14
15 d = (c == 500); operator
16 printf("d = %d\n", d);
17
18 return 0;
19 }
Exercise 5.3:
Enter the program below and run it. Observe the output.
1
#include <stdio.h>
2
3
int main()
4
{
5
int a = 5, b = 5, c = 10, result;
6
7
result = (a == b) && (c > b);
8
printf("(a == b) && (c > b) is %d \n", result);
9
10
result = (a == b) || (c < b);
11
printf("(a == b) || (c < b) is %d \n", result);
12
13
return 0;
14
Question:
Suggest a scenario in the microcontroller where the && operator can be used.
____________________________________________________________________
____________________________________________________________________
Reference: https://www.geeksforgeeks.org/decision-making-c-c-else-nested-else/
The if and if...else constructs are used to make decisions in a program. Based on the
outcome of a test expression, some codes will be executed, while some will be ignored.
Test False
Expression
True
Body of if
Statements
below if..else
The if statement checks whether the test expression inside the parenthesis ( ) is
true or not.
if (test expression)
{ Test expression
// statement(s) to be executed if test needs to evaluate to
// expression is true either true or false
}
The enclosing { and } are optional if there is only one statement inside the statement
block.
Exercise 6.1:
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 int main() {
4 int a = 5, b = 5;
5
6 if (a == b)
7 printf("== is a Relational operator");
8
9 return 0;
10 }
Test False
expression
True
Statements
below if..else
The if… else is used when you want to execute some statement/s if the test expression
is true and execute some other statement/s if it is false.
if (test expression)
{
// statement(s) to be executed if test expression is true
}
else
{
// statement(s) to be executed otherwise
}
Exercise 6.2:
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 int main() {
4 int a = 5, b = 5, c = 10;
5
6 if ((a == b) || (c < b)) {
7 printf("|| is a Logical OR operator\n");
8 }
9 else {
10 printf("Both conditions (a == b) and (c < b) are false\n");
11 }
12 return 0;
13 }
Modify the values of a or b so that the flow can go to the else block.
For multiple options, if, else if statement can be used. The if and else-if statements are
executed from top down. As soon as one of the conditions is true, the statement
associated with that if is executed, and the rest of the else if is bypassed. If none of the
conditions are true, then the final else statement will be executed.
Exercise 6.3:
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 int main() {
4 float x = 100.0;
5
6 if (x > 100)
7 printf("%.2f is greater than 100.", x);
8 else if (x < 100)
9 printf("%.2f is less than 100.", x); Note that the else
10 else construct is not
11 printf("%.2f is equal to 100.", x); followed with a
12 condition next to it.
13 return 0;
(Unlike if and else-
14 }
if).
Change the value of x so that the statements at line 7 and 9 can also be executed.
Note that it is not mandatory to have the final else. For example, the following statements are
also valid.
if (test expression 1)
// statement(s) to be executed if test expression 1 is true
else if (test expression 2)
// statement(s) to be executed if test expression 2 is true
else if (test expression 3)
// statement(s) to be executed if test expression 3 is true
Reference: https://www.geeksforgeeks.org/loops-in-c-and-cpp/?ref=lbp
A for loop is a repetition control structure which allows a loop body to be executed a
specific number of times.
Flow 1 2 3
•
• After executing loop body, this
If condition evaluates to
• expression increments or
true, execute the body of decrements the loop variable
Initialise loop counter to the loop and go to update by some value. For example:
some value. For statement. If false, exit a++;. The flow then goes back
example: int a = 1;. from the loop. to check the test condition
Exercise 7.1:
Enter the program below and run it. Observe the output.
1 #include <stdio.h>
2
3 int main()
4 {
5 int a;
6
7 for (a = 1; a <= 5; a++)
8 {
9 printf("Loop #%d\n", a);
10 }
11 return 0;
12 }
For for loop, the number of iterations is known beforehand. On the other hand, while
loops are used in situations where we do not know the exact number of iterations of loop
beforehand. The loop execution is terminated based on the test condition.
Similar to the for loop, the syntax of the while loop consists of three statements –
initialisation statement, test condition, update statement. The main difference is the
placement of these three statements.
Reference: https://www.geeksforgeeks.org/c-arrays/
Array Elements
Array 1 3 6 23 99
0 1 2 3 4 Array Indices
Declaring an Array
An array is declared like any other variable before we can use it.
We declare an array by specifying its name, the data type of its elements, and the size
(number of elements). When an array is declared, the compiler allocates a memory block
of the specified size to the array name.
During Declaration...
An array can be initialised when it is declared. This is shown in the two examples
below.
Initialising array:
sevseg_pattern[0] = 0b00110101;
sevseg_pattern[1] = 0b11010011;
Array Elements
1 3 6 23 99
0 1 2 3 4 Array Indices
Reference: https://www.geeksforgeeks.org/c-functions/
A function is a group of code that does a specific task. The earliest example of a function
that you have encountered in C was the main() function.
Besides the main() function, you can also write other functions or make use of provided
functions. The former is known as user defined functions, while the latter is known as
library functions. For example, printf() is a library function.
As you have seen in Section 2, the block of a statements belonging to a function are
enclosed within the { } braces.
It is encouraged to use functions in program design. A function is the basic building block
that provides modularity and code reusability especially in large and complex programs.
Using Functions
In order to define a function and use it in your program, the following three items are
essential.
1. Function declaration
2. Function definition
3. Function call
1. Function Declaration
Just like a variable, a function declaration tells the compiler that there is a function
with the given name residing somewhere in the program. If this function is to be called
in this program file, it needs to be declared in the file.
Declaring a function:
The following illustrates how a function to calculate the volume of a box, is declared.
ending
return type parameter type semicolon
int volume(int len, int width, int height);
2. Function Definition
The function definition consists of the actual statements that are executed whenever
the function is called.
Defining a function:
return
type
int volume(int len, int width, int height)
{
int vol;
Body
vol = len * width * height;
return (vol);
}
return value
In the above example, take note that the return value of the function must be of the
same data type as the return type of the function.
3. Function Call
A function call is a statement that instructs the compiler to execute the function.
Exercise 9.1:
Enter the program below and run it. Observe the output.
#include <stdio.h>
int main() {
int result;
Function call
result = volume(3, 4, 5);
printf("Volume = %d\n", result);
return 0;
}
In C, functions can be designed either with or without parameters. While we have seen
an example of a function returning a value from the exercise above, functions may also
be designed such that they do not return values to the calling functions.
The list below shows the various types of functions that can possibly be designed:
Exercise 9.2:
Enter the program below and run it. Observe the output.
Question:
What is the difference between the functions in Exercise 9.1 and 9.2?
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
2. The compiler will automatically compute the size of the following array as 3 integer
elements. Is it True or False?
int scores[ ] = {36, 45, 53};
Ο True
Ο False
3. What are the different types of a C function according to its return type and
parameters? Tick the options that applies.
Function with no parameters and no return value.
Function with few parameters and no return value.
Function with two parameters and two return values.
Function with one parameter and a return value.
~ End of Lab 1 ~
Exercise 11.1:
The Morse code is a system that uses a series of dots and dashes to represent numbers
and alphabets.
The C program below prints the alphabet ‘S’ in the Morse code, which is represented by
3 dots.
#include <stdio.h>
// Function declaration
void dot(void);
void main()
{
dot(); // Function call
dot();
dot();
}
Hint: Make use of the while loop to fulfil the repeated requirement.
Reflection:
1. Have you added any additional function to complete your task? How does doing so
assisted you?
2. Using what you have learnt in C programming, what would you do if you have to
encode all the alphabets in the Morse code to make it easy for one to send out any
codes?
In this section, you will revise what you have learnt in Year 1 on converting between one
number system to another. This number system can be decimal, binary or hexadecimal.
To indicate a binary number in program writing, we use the 0b prefix, then followed by
the binary number. For example:
0b00001111 is the binary number for 15.
Ponder: Why do you think microcontrollers use binary instead of the most common
decimal system?
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
1. Decimal to Binary
Divide the number by 2, keep track of the remainder
3. Binary to Hexadecimal
Technique
• Group bits in fours, starting on right
10101110112 = ?16
10 1011 1011
2 B B
10101110112 = 0x2BB
4. Hexadecimal to Binary
Technique
• Convert each hexadecimal digit to a 4-bit equivalent binary representation
10AF16 = ?2
1 0 A F
0001 0000 1010 1111
10AF16 = 00010000101011112
Exercise 11.2:
Convert the following: Note: Do not use a calculator!
Decimal Binary Hexadecimal
33
0b1110101
0x1AF
These are the reserved words or keywords in C programming language, and they must
be written in lower case.
The table below compares the basic structure of a C program with one in Python.
C Program Python
Uses // for comment. Uses the # symbol.
The main() function is the entry point to the Not necessary to have a main
program. Every program must have one and function. The Python interpreter
only one main() function. executes from the top of the file.