(Ebook) C Programming on Raspberry Pi: Develop innovative hardware-based projects in C by Dogan Ibrahim ISBN 9783895764325, 3895764329 All Chapters Instant Download
(Ebook) C Programming on Raspberry Pi: Develop innovative hardware-based projects in C by Dogan Ibrahim ISBN 9783895764325, 3895764329 All Chapters Instant Download
com
https://ebooknice.com/product/c-programming-on-raspberry-pi-
develop-innovative-hardware-based-projects-in-c-36304238
OR CLICK HERE
DOWLOAD EBOOK
https://ebooknice.com/product/raspberry-pi-for-radio-amateurs-36304276
ebooknice.com
ebooknice.com
https://ebooknice.com/product/raspberry-pi-hardware-projects-1-4706072
ebooknice.com
(Ebook) Raspberry Pi Hardware Projects 2 by Andrew
Robinson, Mike Cook ISBN 9781118588901, 9781118723906,
1118588908, 1118723902
https://ebooknice.com/product/raspberry-pi-hardware-
projects-2-50783782
ebooknice.com
ebooknice.com
https://ebooknice.com/product/raspberry-pi-hardware-reference-54981260
ebooknice.com
ebooknice.com
ebooknice.com
books
books books
C Programming on
C Programming
Dogan Ibrahim
Dogan Ibrahim
an Elektor Publication
● This is an Elektor Publication. Elektor is the media brand of
Elektor International Media B.V.
78 York Street
London W1H 1DP, UK
Phone: (+44) (0)20 7692 8344
© Elektor International Media BV 2021
First published in the United Kingdom 2021
● All rights reserved. No part of this book may be reproduced in any material form, including
photocopying, or storing in any medium by electronic means and whether or not transiently or incidentally
to some other use of this publication, without the written permission of the copyright holder except in
accordance with the provisions of the Copyright, Designs and Patents Act 1988 or under the terms of a
licence issued by the Copyright Licensing Agency Ltd, 90 Tottenham Court Road, London, England W1P 9HE.
Applications for the copyright holder's written permission to reproduce any part of this publication should be
addressed to the publishers. The publishers have used their best efforts in ensuring the correctness of the
information contained in this book. They do not assume, and hereby disclaim, any liability to any party for
any loss or damage caused by errors or omissions in this book, whether such errors or omissions result from
negligence, accident or any other cause.
● ISBN: 978-3-89576-431-8
● EISBN: 978-3-89576-432-5
● EPUB: 978-3-89576-433-2
● Preface
The Raspberry Pi 4 is the latest credit-card sized computer that can be used in many
applications, such as audiovisual media centers, desktop computers, industrial control,
robotics, and many more domestic and commercial applications. In addition to the many
features found in other versions of Raspberry Pi, The Pi 4 also offers Wi-Fi and Bluetooth,
making it highly desirable in remote and internet-based control and monitoring applications.
The Raspberry Pi has traditionally been programmed using Python. Although Python is
a very powerful language, many programmers may not be familiar with using it. The C
language is probably the most commonly used programming languages. All embedded
microcontrollers can be programmed using the C language these days. The C language
is taught in all technical colleges and universities - almost all engineering students are
familiar with the use of this language in their projects.
This book is about using C with Raspberry Pi to develop various hardware-based projects.
Two of the most popular C libraries, wiringPi and pigpio are used.
The book starts with an introduction to the C language and most students and newcomers
will find this chapter invaluable. Many projects are provided in the book, including using
Wi-Fi and Bluetooth to establish communication with smartphones.
The book includes many sensors and hardware-based projects. Both wiringPi and pigpio
libraries are used in all projects. Complete program listings are given with full explanations.
All projects given in the book have been fully tested and work. The following sub-headings
are used in the projects where applicable:
• Project title
• Project description
• Aim of the project
• Block diagram
• Circuit diagram
• Program listing
wiringPi and pigpio program listings of all Raspberry Pi projects developed in the book are
available on the Elektor website. Readers can download and use these programs in their
projects. Alternatively, they can modify the supplied programs to suit their applications.
I hope readers find this book helpful and enjoy reading it.
●6
Table of Contents
Table of Contents
● Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
●7
C Programming on Raspberry Pi
3.2.17 ● Unions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
3.2.18 ● Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
3.3 ● Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
●8
Table of Contents
Chapter 7 ● I2C Bus Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
7.1 ● Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
7.2 ● The I2C Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
7.3 ● Project 1 – Port expander . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
7.4 ● Project 2 – EEPROM memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
7.5 ● Project 3 – TMP102 temperature display . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
7.6 ● Project 4 – I2C LCD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
7.7 ● Project 5 – Using the pigpio library with I2C – TMP102 temperature display . . . 237
7.8 ● Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
●9
C Programming on Raspberry Pi
12.13 ● Support for other chips and add-on boards . . . . . . . . . . . . . . . . . . . . . . . 310
12.14 ● Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
● 10
Table of Contents
● Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
● 11
C Programming on Raspberry Pi
1.1 ● Overview
In this chapter, we will learn how to install the latest operating system (Raspbian Buster)
on the Raspberry Pi 4. We will also learn the different ways that Python can be used to
develop applications. Notice the installation process given below applies to all Raspberry Pi
models unless otherwise specified.
Raspbian Buster is the latest operating system for the Raspberry Pi. This section provides
the steps necessary for installing this operating system on a new blank SD card, ready to
use with Raspberry Pi 4. You will need a micro SD card with a capacity of at least 8GB (16
GB is preferable) before installing the new operating system.
The steps to install the Raspbian Buster operating system are as follows:
• Download the Buster image to a folder on your PC (e.g. C:\RPIBuster) from the
following link by clicking the Download ZIP under section Raspbian Buster with
desktop and recommended software (see Figure 1.1). At the time of writing this
book, the file was called: 2020-02-13-raspbian-buster-full.img. You may have to
use the Windows 7Zip software to unzip the download due to some features not being
supported by older zip software.
https://www.raspberrypi.org/downloads/raspbian/
● 12
Chapter 1 ● Installing the Operating System on Raspberry Pi
• Put the blank micro SD card into the card slot of your computer. You may need an
adapter to do this.
• Download Etcher to your PC to flash the disk image. The link is (see Figure 1.2):
https://www.balena.io/etcher/
• Double click to open Etcher and then click Select image. Select the Raspbian Buster
file you downloaded and unzipped.
• Click Select target and select the micro SD card.
• Click Flash (see Figure 1.3). This may take several minutes, wait until it is finished.
The program will then validate and unmount the micro SD card. You can remove your
micro SD card after it is unmounted.
● 13
C Programming on Raspberry Pi
Your micro SD card now has been loaded with the Raspberry Pi operating system. The
various options now are as follows:
If you are making a direct connection to your Raspberry Pi using a monitor and keyboard,
just insert the SD card into the card slot and power-up your Raspberry Pi. After a short
while, you will be prompted to enter the login details. The default values are username: pi,
password: raspberry.
You can now start using your Raspberry Pi either in command mode or in desktop mode. If
you are in command mode, enter the following command to start the GUI mode:
pi@raspberrypi:~ $ startx
• Move down to Boot Options and press Enter to select (Figure 1.4).
• Select Desktop / CLI and then select Desktop Autologin to boot automatically into
GUI mode.
• Click OK and accept to reboot the system. The system will be in GUI mode next time
it reboots.
• You can change your selections to boot in command mode if you wish by selecting
Console in Boot Options.
You may now want to connect your Raspberry Pi to the internet either to access it remotely
from a PC or to use the internet. If your Raspberry Pi is equipped with an ethernet port
(e.g. Raspberry Pi 2/3/4), you can directly connect to your Wi-Fi router using an ethernet
cable. You can find the IP address of your connection by entering the command: ifconfig in
command mode.
Alternatively, you may want to connect your Raspberry Pi to Wi-Fi and access it remotely.
● 14
Chapter 1 ● Installing the Operating System on Raspberry Pi
• Move down to Interface Options and select SSH and enable it.
• If you are in GUI mode, click the Wi-Fi icon at the top right hand of the screen and
enable Wi-Fi. Note the IP address allocated automatically to your Raspberry Pi.
• You can now remotely access your Raspberry Pi using terminal emulation software,
such as Putty (see Section 1.4 and 1.5).
If you do not have a suitable monitor and keyboard to directly connect to your Raspberry Pi,
you will have to use a networked connection and remotely access your Raspberry Pi using a
PC. There are two options: connection using an Ethernet cable, and connection over
Wi-Fi.
https://notepad-plus-plus.org/downloads/v7.8.5/
https://www.advanced-ip-scanner.com
• Run the software and look for your Raspberry Pi. You do not have to install the software
to run it. Click Run portable version, and then Scan. As shown in Figure 1.5, the IP
address of the author’s Raspberry Pi was 191.168.1.202.
● 15
C Programming on Raspberry Pi
• You can now use Putty to log in to your Raspberry Pi (see Section 1.4 and 1.5)
Alternatively, you can find the IP address of your Raspberry Pi by opening the command
prompt on your PC with administrator privilege (by right-clicking to accepting to run as an
administrator) and then inputting the command: ping raspberrypi.home as shown in
Figure 1.6.
It is also possible to find the IP address of your Raspberry Pi using your smartphone. Many
apps can be used to find out who is currently using your Wi-Fi router. e.g. Who’s On My
Wi-Fi – Network Scanner by Magdalm.
Connection using Wi-Fi: This is the preferred method to access your Raspberry Pi and is
the one used by the author. Here, as described in Chapter 1, the Raspberry Pi can be placed
anywhere you like within the range of the Wi-Fi router and is easily accessed from your PC
using Putty (see Section 1.4 and 1.5).
https://notepad-plus-plus.org/downloads/v7.8.5/
● 16
Chapter 1 ● Installing the Operating System on Raspberry Pi
country=GB
update_config=1
ctrl_interface=/var/run/wpa_supplicant
network={
scan_ssid=1
ssid="MySSID"
psk="MyPassword"
}
• Copy the file (save) to the boot folder on your SD card with the name: wpa_
supplicant.conf.
• Insert the SD card back into your Raspberry Pi and power-up the device.
• Use Advanced Ip Scanner or one of the methods described earlier to find out the IP
address of your Raspberry Pi.
• Log in to your Raspberry Pi remotely using Putty on your PC (see Section 1.3 and 1.4).
• After logging in, you are advised to change your password for security reasons. You
should also run sudoraspi-config from the command line to enable VNC, I2C, and
SPI as they are useful interface tools that can be used in your future GPIO based work.
It is much easier to remotely access the Raspberry Pi over the internet: for example
using a PC rather than connecting a keyboard, mouse, and display to it. Before being able
to remotely access the Raspberry Pi, we have to enable SSH by entering the following
command in a terminal session (if you have followed the steps given earlier, SSH is already
enabled and you can skip the following command):
Go to the configuration menu and select Interface Options. Go down to P2 SSH and
enable SSH. Click <Finish> to exit the menu.
You should also enable VNC so the Raspberry Pi Desktop can be accessed graphically over
the internet. This can be done by entering the following command in a terminal session:
Go to the configuration menu and select Interface Options. Go down to P3 VNC and
enable VNC. Click <Finish> to exit the menu. At this stage you may want to shut down or
restart your Raspberry Pi by entering one of the following commands in command mode:
● 17
C Programming on Raspberry Pi
https://www.putty.org/
Simply double click to run it and the Putty startup screen will be displayed. Click SSH and
enter the Raspberry Pi IP address, then click Open (see Figure 1.7). The message shown in
Figure 1.8 will be displayed the first time you access the Raspberry Pi. Click Yes to accept
this security alert.
● 18
Chapter 1 ● Installing the Operating System on Raspberry Pi
You will be prompted to enter the username and password. Notice the default username
and password are:
username: pi
password: raspberry
You now have a terminal connection with the Raspberry Pi and can type in commands,
including the sudo privileged administrative commands.
passwd
You can use the cursor keys to scroll up and down through the commands you’ve previously
entered in the same session. You can also run programs although not graphical programs.
By default, the Putty screen background is black with white foreground characters. The
author prefers to have white background with black foreground characters, with the
character size set to 12 points bold. The steps to configure the Putty with these settings
are given below. Notice that in this example these settings are saved with the name RPI4
so that they can be recalled whenever the Putty is restarted:
• Restart Putty.
• Select SSH and enter the Raspberry Pi IP address.
• Click Colours under Window.
• Set the Default Foreground and Default Bold Foreground colours to black (Red:0,
● 19
C Programming on Raspberry Pi
Green:0, Blue:0).
• Set the Default Background and Default Bold Background to white (Red:255,
Green:255, Blue:255).
• Set the Cursor Text and Cursor Colour to black (Red:0, Green:0, Blue:0).
• Select Appearance under Window and click Change in Font settings. Set the font
to Bold 11.
• Select Session and give a name to the session (e.g. RPI4) and click Save.
• Click Open to open the Putty session with the saved configuration.
• Next time you re-start the Putty, select the saved session and click Load followed by
Open to start a session with the saved configuration.
You can control your Raspberry Pi via Putty, and run programs on it from your Windows
PC. This however will not work with graphical programs because Windows doesn’t know
how to represent the display. As a result of this, for example, we cannot run any graphical
programs in the Desktop mode. We can get round this problem using some extra software.
Two popular software used for this purpose are: VNC (Virtual Network Connection), and
Xming. Here, we shall be learning how to use the VNC.
VNC consists of two parts: VNC Server and the VNC Viewer. VNC Server runs on the
Raspberry Pi, and the VNC Viewer runs on the PC. VNC server is already installed on your
Raspberry Pi and is enabled as described in Section 1.3 using raspi-config.
The steps to install and use VNC Viewer on your PC are given below:
• There are many VNC Viewers available, but the recommended one is TightVNC which
can be downloaded from the following web site:
https://www.tightvnc.com/download.php
• Download and install TightVNC for your PC. You will have to choose a password during
the installation.
• Enter the following command:
pi@raspberrypi:~ $ vncserver :1
• Start TightVNC Viewer on your PC and enter the Raspberry Pi IP address (see Figure
1.9) followed by :1. Click Connect to connect to your Raspberry Pi.
● 20
Chapter 1 ● Installing the Operating System on Raspberry Pi
When we are using the Raspberry Pi with a Wi-Fi router, the IP address is automatically
allocated by the router. It is possible that every time we start the Raspberry Pi, the Wi-Fi
router will give the Pi another IP address. This makes it difficult to log in as we have to find
the new IP address before we log in.
We can give our Raspberry Pi a static IP address so that every time it starts, the same IP
● 21
C Programming on Raspberry Pi
address is allocated from the Wi-Fi router. The IP address is given by the DHCP protocol
running on the Wi-Fi router.
Before setting a static IP address, we have to decide what this address will be, and also
make sure that no other devices on our network use this address. We can check this by
logging in to the Wi-Fi router or by displaying the devices on our network using an app on
a smartphone.
You should see the text active: (running) displayed as shown in Figure 1.11 (only part of
the display is shown). Enter Ctrl+C to exit from the display.
• We now need to find the IP address (Default Gateway) and the Domain Name Server
address of our router. This can easily be obtained either from our Wi-Fi router or PC.
The steps to obtain these addresses from a PC are:
• Go to Control Panel on your Windows 10 PC.
• Click Network and Sharing Centre.
• Click Internet as shown in Figure 1.12.
• Click Details. You will see a screen similar to the one shown in Figure 1.13 where you
● 22
Chapter 1 ● Installing the Operating System on Raspberry Pi
can see the Default Gateway and DNS server addresses. In this example, they are
both: 191.168.1.254.
• You will have to edit the following file: /etc/dhcpcd.conf using a text editor such as
nano. Although you may not be familiar with nano, follow the instructions given here
(nano is described in a later chapter).
• Go to the end of the file using the down arrow key and enter the following lines:
interface wlan0
static ip_address=191.168.1.120/24
static routers=191.168.1.254
staticdomain_name_servers=191.168.1.254
interface eth0
static ip_address=191.168.1.120/24
static routers=191.168.1.254
static domain_name_servers=191.168.1.254
In this example, we chose a static IP address of 191.168.1.120 after making sure there are
no other devices on our network with the same IP address. The suffix /24 is an abbreviation
of the subnet mask 255.255.255.0. You have to make sure you only change the last digit of
the IP address. i.e. choose an address in the form 191.168.1.x. wlan0 is for the Wi-Fi link,
and eth0 is for the Ethernet link.
• Reboot your Raspberry Pi and it should come up with the IP address set as required
● 23
C Programming on Raspberry Pi
1.8 ● Summary
In this chapter, we learned how to install the latest Raspberry Pi operating system on an SD
card, and also how to start using the Raspberry Pi remotely. The instructions provided apply
to all versions of Raspberry Pi. Additionally, setting a static IP address for your Raspberry
Pi is demonstrated.
In the next chapter, we will look at various Raspberry Pi program development tools.
● 24
Chapter 2 ● Raspberry Pi Program Development
2.1 ● Overview
In the last chapter, we learned how to install Raspbian Buster on a Raspberry Pi SD card. In
this chapter, we will learn how to develop programs using Raspberry Pi 4. We will develop
a very simple example project and learn how to use Python and C. Although Python is not
the topic of this book, it will be used in a simple project so that readers can compare Python
with C programming.
A text editor is a very useful tool for creating program source files. Raspberry Pi supports
several text editors including vi, nano, etc. In this section, we will introduce nano which is
normally run from the command line.
As an example, suppose we wish to create a text file called myfile.txt and insert the
following lines into the file:
• Start nano
• Enter the above text into the file (see Figure 2.1). You should see several control codes
at the bottom of the screen.
● 25
C Programming on Raspberry Pi
• Enter Ctrl+X followed by the letter Y to save the file. You should now see the file listed
in your directory if you enter the command:
pi@raspberrypi:~ $ ls myfile.txt
myfile.txt
pi@raspberrypi:~ $
• Let us now edit the file we just created to learn some of the editor commands. Restart
nano as above by specifying the filename.
• Let us search for text starting with the word simple: press Ctrl+W and type simple
and press Enter (see Figure 2.2). You should see the cursor moving to the start of the
word simple. Delete simple and change it to difficult.
• Let us replace the word third with fourth: press Ctrl+\ and type third, and then
fourth when Replace with: is displayed. Press Enter. The message Replace this
instance? will be displayed. Type Y. You should see that the word third is replaced
with fourth.
• Let us delete the second line of text: Move the cursor to the second line and enter
Ctrl+K. You should see all the text on the second line is deleted.
• To recall the line just deleted, enter Ctrl+U.
• To get help on using nano, enter Ctrl+G. An example help screen is shown in Figure
2.3. Enter Ctrl+N to display the next page, and Ctrl+P to display the previous page.
Enter Ctrl+X to close the help screen.
● 26
Chapter 2 ● Raspberry Pi Program Development
As a summary, some of the more useful nano shortcuts are given below:
Ctrl+J: Justify.
In this chapter, we will develop a simple project using both Python and C which will display
the message Hello From Raspberry Pi 4 on your PC screen. This project aims to show
how a project can be created and then run on Raspberry Pi.
As described below, there are four methods we can employ to create and run Python
programs on Raspberry Pi:
● 27
C Programming on Raspberry Pi
Using this method, we will log in to our Raspberry Pi remotely using SSH and create and run
our program interactively in command mode. This method is excellent for small programs.
The steps are as follows:
• Log in to your Raspberry Pi 4 using SSH (or through a connected monitor and keyboard).
• On the command prompt, enter python3. You should see the Python command mode
which is identified by the following three characters: >>>.
• Type the program:
• The text required will be displayed interactively on the screen as shown in Figure 2.5.
Enter Ctrl+Z to exit Python.
In this method, we will log in to our Raspberry Pi using SSH as before and then create a
Python file. A Python file is simply a text file with the extension .py. We can use a text
editor, e.g. nano to create our file. In this example, a file called hello.py is created using
nano. Figure 2.6 shows the contents of hello.py. This figure also shows how to run the file
using Python 3. Notice the program is run by entering the command:
Using this method, we will log in to our Raspberry Pi in desktop mode using VNCViewer (if
we do not have a monitor directly connected) and create and run our program in GUI mode.
We will be using Thonny which is used to create, debug, and run Python 3 programs.
● 28
Chapter 2 ● Raspberry Pi Program Development
Thonny is an easy to use tool which is only available for Python 3. The nice thing about
Thonny is that it formats code while it is entered from the terminal. For example, all
statements in the body of a while loop are automatically and correctly indented.
• Click Applications menu, then Programming, and select Thonny Python IDE as
shown in Figure 2.7
• The Thonny startup screen will be displayed as shown in Figure 2.8. The screen has two
parts: The program is written in the upper part. The lower part is the shell where the
results of the program are displayed. We can also run Python 3 commands interactively
in the lower part of the screen. In the upper part, we have the usual menu items found
in most GUI type displays. Menu option File is used to create a new file, open an
existing file, close, save, or print a file. Menu option Edit is used to undo, cut, paste,
select, find, replace, and so on. Option View is used to enable us to view files, heap,
notes, stack, variables, and so on. Menu option Run is used to run or debug a program.
Menu option Device is used to soft reboot, upload a current script as main script, and
so on. Menu option Tools is used to manage packages, manage plug-ins, configure
Thonny, and so on. Finally, the Help menu option is used to get help on using Thonny.
● 29
C Programming on Raspberry Pi
• Click File and save your program by giving it a name. You do not have to specify the
file extension as this is automatically added by Thonny.
• Click Run and you should see the program output on the lower part of the screen as
shown in Figure 2.10.
● 30
Chapter 2 ● Raspberry Pi Program Development
Thonny provides the option to debug a program, where we can single-step through a
program and display the variables as the program is stepped through. As an example, let
us debug the program given in Figure 2.9. The steps are:
In this method, we will use Mu to create and run our Python example program. Mu is a very
easy to use Python editor and Integrated Development Environment (IDE) for beginners.
Mu is installed by default with the Raspbian Buster operating system and can be started by
clicking the Applications Menu, followed by Programming and then Mu (see Figure 2.11).
● 31
C Programming on Raspberry Pi
• Enter Mu in the search box and click on Mu. Click Apply to install the software (Figure
2.13).
● 32
Chapter 2 ● Raspberry Pi Program Development
Mu can also be installed from the command line using the command:
Figure 2.14 shows the startup screen of Mu where the statement to display the message
Hello Form Raspberry Pi 4 is entered.
The menu options are listed on the top of the screen. Click Run to execute the program. The
result will be displayed on the bottom part of the screen as shown in Figure 2.15.
Interested readers can learn how to use other menu options but this is outside the scope
of this book.
● 33
C Programming on Raspberry Pi
Which Method?
The choice of method depends upon the size and complexity of the program we wish to
develop. Small programs can be interactively run without creating a program file. Larger
programs can be created as Python files by using either nano in command mode. Thonny
and Mu can be used to create programs in Desktop GUI mode. Python beginners should
find Mu easy to use.
Programming Raspberry Pi in C is the main topic of this book. We will use nano to create
our C source programs. The programs should have the file extensions .c. Figure 2.16 shows
the program listing our simple project (Program: msg.c).
#include <stdio.h>
int main(void)
{
printf("Hello From Raspberry Pi 4\n");
}
Figure 2.16 Program: msg.c
The header file stdio.h is included at the beginning of the program. The message is printed
using the printf statement. A new-line is printed at the end of the text using the \n keyword.
The program is compiled by entering the following command. Here, gcc is the C compiler,
-o option specifies that the next word (i.e. hello) is the output filename:
pi@rasberrypi:~$ ./hello
Hello From Raspberry Pi 4
pi@raspberrypi:~ $
Notice ./ specifies the file is in our current directory, which is by default /home/pi.
Alternatively you could enter the following command to run the program:
pi@raspberrypi:~ $ /home/pi/hello
Hello From Raspberry Pi 4
pi@raspberrypi:~ $
• If the output option –o is not specified, the compiler creates the executable file
● 34
Chapter 2 ● Raspberry Pi Program Development
• Option –S generates an assembly code listing of the program. In the following example,
the assembly listing is stored in file msg.s:
• Option –save-temps creates executable file (a.out), assembly file, compile file, and
list file:
• Option –l links with the specified library. In the following example, the code is linked
with a library called wiringPi:
• Option –v displays all the steps gcc takes while compiling the program:
• Option @ can be used to read the compiler options from a file. For example, assume
MyOptions contains the lines:
-Wall –o MyOutputFile
Then, program msg.c can be compiled with the above options as:
2.6 ● Summary
In this chapter, we learned how to develop Python 3 and C programs using several
methods. The choice of method for Python depends entirely on the user. In this book, we
are interested in developing programs using C. Therefore, the remainder of this book is
about the C language and its use with Raspberry Pi.
● 35
C Programming on Raspberry Pi
In the next chapter, we will make an introduction to C. Readers who are familiar with C can
skip most sections.
● 36
Chapter 3 ● C Programming for Raspberry Pi
3.1 ● Overview
In this chapter we will be look at the basic principles of programming using C. There are
hundreds of books, tutorials and application notes on programming using C and therefore
this chapter is not intended to teach C programming in detail.
3.2.1 ● Variables
As we have seen earlier, printf is used to display data and text on the screen. Data can be
inputted from the keyboard using the scanf statement. An example is given below.
Example 3.1
Write a program to read the base and height of a triangle and then calculate and display
its area.
Solution 3.1
/*-----------------------------------------------------------
AREA OF A TRIANGLE
==================
● 37
C Programming on Raspberry Pi
int main(void)
{
float Base, Height, Area;
printf("\nArea of a Triangle\n\n");
printf("Enter base: ");
scanf("%f", &Base);
printf("Enter Height: ");
scanf("%f", &Height);
Area = Base * Height / 2.0;
printf("Area = %f\n", Area);
return 0;
}
Figure 3.1 Program: TriangleArea.c
At the beginning of the program, variables Base, Height and Area are declared as floating-
point variables. The program then displays the heading Area of a Triangle. New lines are
printed before and after displaying this heading. The text Enter base: is displayed and the
user is requested to enter the base of the triangle which is stored in variable Base. Notice
that scanf requires the memory address of the variable to store the data. Then height is
requested from the user. The area of the triangle is calculated and displayed on screen.
Figure 3.2 shows an example run of the program.
We can change the number of decimal places using the %f statement. The general format
of this statement is:
%n.df where n is the total length of the number to be displayed and d is the
number
● 38
Chapter 3 ● C Programming for Raspberry Pi
For example, to display area with one digit after the decimal point, we can use the statement:
Some other example output formats are (assuming the number to be displayed is 62.0):
%4.2 62.40
%5.2 62.40
%6.3 62.400
%c character
%d integer number
%s string
%u unsigned decimal integer
%lu unsigned decimal long integer
%o octal number
%x, %X hexadecimal number
%e exponential number
Example 3.2
In this example, we will again calculate the area of a triangle but its base and height will
be entered on the same line.
Solution 3.2
/*-----------------------------------------------------------
AREA OF A TRIANGLE
==================
● 39
C Programming on Raspberry Pi
int main(void)
{
float Base, Height, Area;
printf("\nArea of a Triangle\n\n");
printf("Enter base and height: ");
scanf("%f %f", &Base, &Height);
Area = Base * Height / 2.0;
printf("Area = %6.3f\n", Area);
return 0;
}
Figure 3.3 Program: TriangleArea2.c
This program is very similar to the one provided in Example 1, but scanf is used to read
both the base and height of the triangle with a space separating the two entries. Figure 3.4
shows an example run of the program.
3.2.3 ● Comparison
3.2.4 ● Operators
x + y addition
x – y subtraction
x * y multiplication
x / y division
x % y remainder of x/y
x & y bitwise AND
x | y bitwise OR
● 40
Chapter 3 ● C Programming for Raspberry Pi
x ^ y bitwise exclusive OR
~x complement
!x logical NOT
x << y bit shift left
x >> y bit shift right
Flow control statements constitute very important statements in all programming languages.
These statements enable programmers to form conditional program executions, selections,
and iterations (loops).
Conditional statements
if…else
The if…else block of statements are the main conditional statements. The general format
of an if…else block is:
if(condition is true)
{
execute these statements
…………………………
…………………………
}
else
● 41
C Programming on Raspberry Pi
{
execute these statements
………………………….
………………………….
}
If there is only one statement inside an if block, there is no need to use a curly bracket:
if(condition is true)
execute a single statement;
Example 3.3
Write a program to read two numbers from the keyboard and calculate their average. If
the average is greater than 10, display Average is greater than 10. If on the other hand
the average is less than 10, display Average is less than 10. If on the other hand, the
average is equal to 10, display Average is 10.
Solution 3.3
Figure 3.5 shows the program listing (Program: Average.c). The program reads two
floating-point numbers into variables no1 and no2. The average is calculated and stored in
variable average. A message is then displayed depending on whether the average is equal
to 10, greater than 10, or less than 10. Figure 3.6 shows an example run of the program.
/*-----------------------------------------------------------
AVERAGE OF 2 NUMBERS
====================
int main(void)
{
float no1, no2, average;
printf("\nAverage of two numbers\n\n");
printf("Enter two numbers: ");
● 42
Chapter 3 ● C Programming for Raspberry Pi
return 0;
}
Figure 3.5 Program: Average.c
switch
The switch statement is another conditional statement that is used to test a variable
against several conditions, and do different things for each condition. The general format of
the switch statement is as follows:
switch (variable)
{
condition 1: do some statements
condition 2: do some statements
condition 3: do some statements
default: do some statements
}
Notice that default is optional and if none of the conditions are satisfied, the statements
under default are executed.
Example 3.4
● 43
C Programming on Raspberry Pi
Solution 3.4
Figure 3.7 shows the required program (Program: calculator.c). The function scanf is
used to read the two numbers and the required operation on the same line. A switch
statement is used to perform the required calculation. Notice the conditions are specified
using the case statement followed by the condition. If for example, the user entered +,
the two numbers added together and the sum is stored in variable result, which is then
displayed. The break statements make sure that the switch block terminates after the
contents of a condition are executed.
/*-----------------------------------------------------------
SIMPLE CALCULATOR
=================
int main(void)
{
float no1, no2, result;
char oper;
switch(oper)
{
case ‘+’:
result = no1 + no2;
break;
case ‘-’:
result = no1 - no2;
break;
case ‘*’:
result = no1 * no2;
break;
case ‘/’:
result = no1 / no2;
break;
}
● 44
Chapter 3 ● C Programming for Raspberry Pi
while
This flow control statement is usually used in loops (repetition). The statements inside the
curly brackets are executed as long as the condition is true. Notice if the condition does not
become true inside the curly brackets, the loop is executed forever. Also, if the condition is
false on entry to the loop, the statements inside the loop are never executed. The general
format of this statement is as follows:
while(condition is true)
{
execute these statements
}
Example 3.5
Solution 3.5
The total resistance of resistors connected in series is calculated by adding up the values of all
the resistors. Figure 3.9 shows the required program listing (Program: SerialResistors.c).
At the beginning of the program, the user is asked to enter the number of resistors
connected in series and this is stored in variable no. A while loop is then formed and inside
this loop, the user is asked to enter the value of each resistor. The total resistance is stored
in the variable Total which is displayed on the screen.
● 45
C Programming on Raspberry Pi
/*-----------------------------------------------------------
SERIALLY CONNECTED RESISTORS
=============================
int main(void)
{
int no, k, R, Total;
k = 1;
Total = 0;
● 46
Another Random Scribd Document
with Unrelated Content
A BRIEF
A C C O U NT
OF THE
T R I A L
AT THE
L E T T E R to a F R I E N D.
And when the town-clerk had appeased the people, he said, Ye men of
Ephesus, what man is there that knoweth not how that the city of the Ephesians is
a worshipper of the great goddess Diana, and of the image which fell down from
Jupiter. Seeing then that these things cannot be spoken against, ye ought to be
quiet, and to do nothing rashly. For ye have brought hither these men, which are
neither robbers of churches, nor yet blasphemers of your goddess. Wherefore if
Demetrius, and the craftsmen which are with him, have a matter against any man,
the law is open, and there are deputies; let them implead one another. But if ye
enquire any thing concerning other matters, it shall be determined in a lawful
assembly. For we are in danger to be called in question for this day’s uproar, there
being no cause whereby we may give an account of this concourse.
A BRIEF
A C C O U N T, &c.
London, March 12, 1744.
My dear friend,
Upon this the jury were desired to consider of their verdict. There
seemed to be some little demur amongst them. His Lordship
perceiving it, informed them, “They had nothing to do with the
damages, (that was to be referred to the King’s-Bench) they were
only to consider whether the Defendants were guilty or not.”
Whereupon, in a few minutes, they gave a verdict for the
prosecutors, and brought in all the Defendants, “guilty of the whole
information lodged against them.” I then retired to my lodgings,
kneeled down, and gave thanks, with some friends, to our all-
conquering Emmanuel. Afterwards I went to the inn, prayed, and
returned thanks with the witnesses, exhorted them to behave with
meekness and humility to their adversaries, and after they had taken
proper refreshment sent them home rejoicing. In the evening I
preached on those words of the Psalmist, “By this I know, that thou
favourest me, since thou hast not suffered mine enemy to triumph
over me.” God was pleased to enlarge my heart much. I was very
happy with my friends afterwards, and the next morning set out for
London, where we have had a blessed thanksgiving season, and
from whence I take the first opportunity of sending you as many
particulars of the occasion, progress, and issue of our trial, as I can
well recollect. What report his Lordship will be pleased to make of
the case, and how the Defendants will be dealt with, cannot be
known till next term; when I know I shall apprize you of it, as also of
our behaviour towards them.――In the mean while let me entreat
you to give thanks to the blessed Jesus in our behalf, and to pray
that his word may have free course, may run and be glorified, and a
stop be put to all such rebellious proceedings. I remain, Sir,
George Whitefield.
⁂ For more particulars of this affair, see Volume II. Letters 526,
527, 529, 545, 549, and 550.
A
L E T T ER
TO THE
IN
A N S W ER
TO HIS
L E T T E R, &c.
London, May 22, 1744.
Reverend Sir,
I HAVE read your expostulatory letter, and thank you for prefixing
your name. Had the author of the observations been so
ingenuous, he would have saved you and me some trouble; but as
he hath not, and the pamphlet was published in such a way, I cannot
think myself justly chargeable with ill-manners or censoriousness, for
treating him and their Lordships concerned, in the manner I have
done. Our Saviour dealt always very plainly with the rulers of the
Jewish Church; and when one was offended, and said, “Master, thus
saying, thou reproachest us also,” he was so far from recanting, that
he said, “And woe unto you also ye lawyers.” In the same spirit, the
proto-martyr Stephen addressed himself to the Jewish Sanhedrim,
and said unto them, “Ye stiff-necked and uncircumcised in hearts
and ears, ye do always resist the Holy Ghost; as your fathers did, so
do ye.” And however shocking, Rev. Sir, it may appear to you, (page
43d of your letter) for us to urge our Lord’s example and his blessed
apostles, yet I think it quite consistent for a minister, who has
received an apostolical commission at his ordination, “Receive thou
the Holy Ghost now committed unto thee by the imposition of our
hands, &c.” to make use of the example of our Lord and his
apostles, in vindication of his conduct; because Christ left us an
example, that we might follow his steps; and we are called to be
followers of the apostles, as they were of Jesus Christ. I know not
how to give flattering titles, and therefore must stand to it, that they
are false witnesses, however dignified or distinguished, and lay to
my charge a thing that I know not, who tax me with being an open
defier of government, for preaching in the fields. Neither do I think I
have wronged the author of the observations at all, by insinuating,
“That the design and scope of this pamphlet was to represent the
proceedings of the Methodists as dangerous to the church and state,
in order to procure an act of parliament against them, or oblige them
to secure themselves by turning dissenters.” That this was his drift,
(at least that he intended to move the government against the
Methodists in general, and me in particular) I think appears quite
plain from a little two-penny paper lately published, (I suppose by the
same anonymous author) wherein he declares, “That though Mr.
Whitefield has pleaded in behalf of the Methodists, that they are an
harmless and loyal people, yet 1st. He cannot possibly be supposed
to know all the persons, or even one tenth part of those present at
his meetings of 30, 50, or 80000.—2d. When he appoints or holds a
meeting, all people are at liberty to come, and to carry on such
purposes as they think proper.—3d. Such a free and safe resort for
great multitudes to one place, subject to no controul or examination,
is doubtless a great opportunity put into the hands of seditious
persons to raise disturbances.” He adds, “How consistently with the
act of toleration, or with what safety to the public, these field-
preachings may be continued, let the world judge.” If this be not
intended to move the government against me, surely there was
never a motion made against any man living; but with what little
shew of true reasoning I need not mention. Let the world judge.
Here lies the point, Rev. Sir: the generality of the clergy are
offended in their hearts, that his majesty is so mild towards his
harmless and loyal people the Methodists. They have denied the
Methodist preachers the use of their churches, and think, if field-
preaching was put a stop to, Methodism, as they term it, would be
less extensive. But were they to gain their point, and the preachers
to be bound, yet perhaps after all they would find themselves
mistaken, for the word of God would not be bound. And I remember
a saying of the then Lord Chancellor to that holy martyr Bradford,
“Thou hast done more hurt (as he called it) by thy letters and
exhortations since thou hast been in prison, than thou ever didst
before.” However this be, field-preaching is at present the clergy’s
eye-sore. Hence they raise a clamour that it is unlawful. We deny it.
We say the act of toleration urged against us is nothing to the
purpose, for we are true members of the established church; and
that if we were not (quod magno mercenter Atridæ) yet the trial of
Mede and Pen is an adjudged case. But still, if you or any other
person please to move for an information against me, for preaching
in a field, or a street, though I purpose to go abroad shortly, yet I
shall think it my duty to stay some time, to make a legal defence. But
if not, henceforward whatever questions may be put to me in print,
about the lawfulness of field-preaching, they will lie unanswered.
These, Rev. Sir, are the real sentiments of my heart. I think they
are founded on truth and soberness. And if so, blame me not, as you
do (page 21st) for comparing the Church of England, as it now
subsists, to a leaky ship. For is it not too evident that she is not only
leaky, but really sinking, when several of the Right Reverend the
Bishops, and a prebendary of St. Paul’s, can openly plead for works
being a condition of our justification in the sight of God? This was
the particular charge my Lord of London gave his clergy in his last
pastoral letter, “So to explain the doctrine of justification by faith
alone, as not to exclude good works from being a condition of our
justification.” Was the great apostle of the Gentiles now living, what
anathema’s would he pronounce against such Judaizing doctrine?
Was Luther on earth, how would he thunder against such a charge?
For he calls justification by faith alone, articulus stantis aut cadentis
ecclesiæ. This is the great fundamental point in which we differ from
the church of Rome. This is the grand point of contention between
the generality of the established clergy, and the Methodist preachers:
we plead for free justification in the sight of God, by faith alone, in
the imputed righteousness of Jesus Christ, without any regard to
works past, present, or to come. You (Bellarmine like) are for making
your works, conditions (page 17th); “And joining your honest, though
imperfect endeavours to serve and please your Maker, with a hearty
trust and confidence in his everlasting mercies,” (page 42.) You say,
(page 58th) we are very far from building wholly on our morality;” we
say, our morality is not to be built on at all, but that “Christ is the
end of the law for righteousness to every one that believeth.” This,
you think, is one of my errors. But if it be an error, it is a scriptural
error; and so plainly taught in the eleventh article of our church, that
he that runs may read: and however you may blame me for
insinuating, “That some of the clergy may adhere to his majesty only
for his preferments, and consequently not appear altogether so
hearty in a time of danger;” yet I cannot think it an instance of hard-
judging at all. For if persons can deliberately subscribe to the
doctrines of justification by faith alone, and other articles that are
purely Calvinistical, yet so explain them away as plainly to prove
they scarce believe a word of them, I should not wonder if they
turned Jacobites, or went over to the pretender, whenever they saw
it suited their worldly interest so to do.
Thus writes that good man Mr. Eaton. I leave you, Rev. Sir, to
make what use of it you please. You see we have human as well as
divine authority on our side. And yet we are looked upon as
erroneous, and are accordingly denied the churches: and what for?
even for preaching up the doctrine of justification by faith alone; for
which the glorious martyrs of the Church of England burnt in
Smithfield. If this be not like Nero’s setting Rome on fire, and then
charging it upon the christians, I know not what is.
This is really, Rev. Sir, the truth of the case. However, we are
willing to frequent the church, and receive the holy sacrament, if the
clergy please to give us leave. This I think we may do, without being
guilty of the inconsistency you charge us with (page 29th), because
in the 26th article of our church we are taught, “Although in the
visible church the evil be ever mingled with the good, and sometime
the evil have chief authority in the ministration of the word and
sacraments: yet, forasmuch as they do not the same in their own
name, but in Christ’s, and do minister by his commission and
authority, we may use their ministry, both in hearing the word of God,
and in receiving of the sacraments: neither is the effect of Christ’s
ordinance taken away by their wickedness, nor the grace of God’s
gifts diminished from such, as by faith, and rightly do receive the
sacraments ministered unto them, which be effectual, because of
Christ’s institution and promise, although they be ministered by evil
men.” This I think a sufficient vindication, for the methodists keeping
in the church. But if some cannot go thus far, nor bear to hear the
doctrine of justification by faith alone continually preached against,
the preachers must thank themselves if any entirely desert the
church, and run to meeting-houses or elsewhere, to get food for their
souls. For I am persuaded, if the doctrine of justification by faith
alone be banished from our pulpits, people may attend to their lives
end, and yet never have the whole counsel of God (as you think
they may, page 50.) declared unto them.
I could enlarge upon this point, and also answer the charge of
enthusiasm which you bring against me in several parts of your
letter. But I willingly omit it, because I shall have occasion to write
more explicitly on these points in my second answer to the
Observations: I have some reasons for deferring it at present. But I
assure you, Rev. Sir, you must not expect me to treat that
anonymous author with less justice than in my last. For however
worthy perhaps he may be in your sight, I think I shall prove him to
be no better than an unskilful slandering sophister; and if a
clergyman, an unorthodox blind guide.
Indeed you say (page 41st) “We do not oppose or deny the true
scripture doctrine concerning these points, (viz. Free justification, the
new birth, and the in-dwelling of the spirit) but only your account and
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com