Embedded C Programming -  Mark Siegesmund

Embedded C Programming (eBook)

Techniques and Applications of C and PIC MCUS
eBook Download: PDF | EPUB
2014 | 1. Auflage
424 Seiten
Elsevier Science (Verlag)
978-0-12-801470-7 (ISBN)
45,95 € inkl. MwSt
Systemvoraussetzungen
46,71 € inkl. MwSt
Systemvoraussetzungen
  • Download sofort lieferbar
  • Zahlungsarten anzeigen

This book provides a hands-on introductory course on concepts of C programming using a PIC® microcontroller and CCS C compiler. Through a project-based approach, this book provides an easy to understand method of learning the correct and efficient practices to program a PIC® microcontroller in C language. Principles of C programming are introduced gradually, building on skill sets and knowledge. Early chapters emphasize the understanding of C language through experience and exercises, while the latter half of the book covers the PIC® microcontroller, its peripherals, and how to use those peripherals from within C in great detail.

This book demonstrates the programming methodology and tools used by most professionals in embedded design, and will enable you to apply your knowledge and programming skills for any real-life application. Providing a step-by-step guide to the subject matter, this book will encourage you to alter, expand, and customize code for use in your own projects.


  • A complete introduction to C programming using PIC microcontrollers, with a focus on real-world applications, programming methodology and tools
  • Each chapter includes C code project examples, tables, graphs, charts, references, photographs, schematic diagrams, flow charts and compiler compatibility notes to channel your knowledge into real-world examples
  • Online materials include presentation slides, extended tests, exercises, quizzes and answers, real-world case studies, videos and weblinks


Mark Siegesmund is a software engineer with over 30 years of experience in embedded sytems within the military, industrial and commercial sectors. He is the founder of Custom Computer Services, Inc. (CCS). CCS specializes in embedded software and hardware, offering development tools for Microchip MCUs and DSCs, as well as a line of embedded Ethernet development.
This book provides a hands-on introductory course on concepts of C programming using a PIC(R) microcontroller and CCS C compiler. Through a project-based approach, this book provides an easy to understand method of learning the correct and efficient practices to program a PIC(R) microcontroller in C language. Principles of C programming are introduced gradually, building on skill sets and knowledge. Early chapters emphasize the understanding of C language through experience and exercises, while the latter half of the book covers the PIC(R) microcontroller, its peripherals, and how to use those peripherals from within C in great detail. This book demonstrates the programming methodology and tools used by most professionals in embedded design, and will enable you to apply your knowledge and programming skills for any real-life application. Providing a step-by-step guide to the subject matter, this book will encourage you to alter, expand, and customize code for use in your own projects. A complete introduction to C programming using PIC microcontrollers, with a focus on real-world applications, programming methodology and tools Each chapter includes C code project examples, tables, graphs, charts, references, photographs, schematic diagrams, flow charts and compiler compatibility notes to channel your knowledge into real-world examples Online materials include presentation slides, extended tests, exercises, quizzes and answers, real-world case studies, videos and weblinks

Half Title 
2 
Title Page 4
Copyright 5
Contents 6
Introduction 16
Chapter 1 C Overview and Program Structure 18
C Source Code 18
Comments 18
Program Structure 19
C Preprocessor Directives 19
Functions 19
Declarations 20
Statements and Expressions 20
Time 21
Typing Accuracy 21
Text Formatting 22
Compatibility Notes 22
Summary 22
Quiz 25
Chapter 2 Constants 28
Bits, Bytes, Etc. 28
Bits 28
Nibbles 28
Bytes 28
Syntax of C Constants 29
Binary 29
Decimal 31
Signed Integers 31
Hexadecimal 32
Octal 34
Floating Point 35
Fixed Point 35
Characters 35
String of Characters 36
True and False 37
Const 38
Tri-Graph Sequences 38
Compatibility Notes 40
Design Documentation 40
Summary 40
Quiz 42
Chapter 3 Preprocessor Directives 44
Standard Preprocessor Directives 44
#define id text 44
#include < filename>
#ifdef#ifndef#else#endif#undef 46
#if#else#elif#endif 47
#error 47
#nolist#list 48
Compatibility Notes 48
Nonstandard Pragmas 49
#warning 49
#use delay 49
About Frequency 49
#use rs232 (options) 50
#fuses options 50
#locate id=address 51
#byte id=x#word id=x 51
#bit id=x.y 52
#reserve address 52
Bootloaders 52
#rom address={data} 52
#id data 53
Other Pragmas 53
Summary 54
Quiz 56
Chapter 4 Data Variables and Types 60
Data Types 60
Characters 60
Integers 61
Compatibility Note 61
Integer Format 62
Enumerated Types 62
Fixed Point 63
Floating Point 63
Interpretation Help 63
Floating-Point Format 64
Void 64
typedef 65
Declaring Variables 65
Identifiers 66
Scope of a Variable 67
Life of a Variable 68
More Qualifiers 68
Design Documentation 69
RAM 70
Summary 71
Quiz 73
Chapter 5 Expressions and Operators 76
Mathematical Operators 76
Compatibility Notes 76
Operator Precedence 77
Expression Type and Type Conversion 77
Relational Operators 79
Binary Bitwise Operators 80
Compatibility Notes 81
Assignment Operators 81
Increment/Decrement Operators 81
Other Operators 82
Sequence Points 84
Expression Examples 84
Summary 85
Quiz 87
Chapter 6 Statements 90
if Statement 91
while Loops 94
for Loop 98
Jump Statements 99
switch/case Statement 101
Side Effects 102
Nesting, Indentation, and Use of Braces 103
Design Documentation 104
Program Complexity 105
Summary 107
Quiz 108
Chapter 7 Functions 112
main() FUNCTION 112
Function Definitions 112
Function Parameters 115
Compatibility Notes 116
Reference Parameters 116
Default Parameters 117
Overloaded Functions 117
Return Values 118
Inline Functions 119
Nested Functions 119
Recursive Functions 119
A Little More on Sequence Points 119
Well-Structured Programs 120
Design Documentation 122
Implementation Details 122
Summary 123
Quiz 124
Chapter 8 Arrays 128
Array Initializers 128
Constant Arrays 129
String Variables 129
Dimensionless Arrays 130
Multidimensional Arrays 130
Index Range 131
Example Array Usage 131
Lookup Tables 133
Searching Arrays 134
Sorting Arrays 136
Summary 137
Quiz 138
Chapter 9 Structures 142
Structure Nesting and Arrays 143
Structure Layout in Memory 144
Bit Fields 145
Unions 146
Example of Structures in a Program 148
Summary 149
Quiz 150
Chapter 10 Memory and Pointers 154
Memory 154
Address-of Operator 156
Indirection Operator 156
Forcing a Variable Address 156
Pointer Types 157
Pointer Math 157
Back to Subscripts 158
Back to Function Parameters 158
Back to Structures 159
Function Pointers 160
Other Uses for Pointers 161
Bad Ideas 162
Common Mistakes 162
ROM Pointers 162
User-Defined Memory 163
Compatibility Note 164
Over the Hill 164
Summary 165
Quiz 166
Chapter 11 Built-in Functions 170
Math 171
Memory 171
Dynamic Memory 172
A Few More Cool Functions 173
Variable Argument List 174
Text Input/Output 175
Implementation Constants 179
Compatibility Notes 179
Bit and Byte Manipulation 179
Non-volatile Memory 180
Watchdog Timer 183
Delays 184
Multiple Clock Speeds 184
A Few More Standard Functions 185
Coming Up 185
Summary 186
Quiz 188
Chapter 12 Strings 192
String Copy and Length 192
String Search 194
String Compare 195
String Manipulation 195
String Input and Output 196
String Conversion to/from Numbers 197
Character Manipulation 198
Unicode 198
Constant String Management 199
Summary 199
Quiz 200
Chapter 13 Function-Like Macros 206
Arguments 207
Macro Names 208
Concatenation Operator 208
Stringize Operator 208
Variadic Macro Syntax 210
Function-Like Macros vs. Inline Functions 211
Readability 211
Advanced Example 212
Debugging Macro Problems 213
Summary 213
Quiz 215
Chapter 14 Conditional Compilation 218
Basic Directives 220
Relational Expressions 221
Special Macros 221
Special Defines 222
Global Defines 222
Strange Errors 222
Examples of Conditional Compilation 223
Summary 224
Quiz 224
Chapter 15 PIC® Microcontroller 228
CPU 229
Stack 230
Working Register 230
Special Function Registers 230
Program Memory 231
Instructions 231
Clock 231
Reset 233
Sleep 233
Interrupts 233
Configuration Bits 234
Peripherals 234
Minimal Hardware Connections 234
Device Programming 234
Hex Files 238
Power-Up Considerations 239
Clock Configurations 239
Debugging 239
Bootloading 240
Summary 241
Quiz 242
Chapter 16 Discrete Input and Output 246
Input Voltages 246
Drive Current 247
Driving More Current 248
Open Collector Outputs 249
Direction 250
Button Input 251
Pull-Ups 251
Debounce 252
Filtering 253
Memory-Mapping Ports 254
Summary 256
Quiz 258
Chapter 17 Interrupts 262
Simple Interrupt Example 262
Where Does the Time Go? 263
Debounce Revisited 264
It’s Not Always a Good Time to Interrupt 265
Why Do We Need Interrupts? 267
What is Really Happening 268
Interrupt Flag (IF) 268
Interrupt Enable Flag (IE) 269
Global Interrupt Enable Flag (GIE) 269
Interrupt Handling 269
Handle Your Interrupts Right 269
Multiple Interrupt Considerations 270
12-Bit Opcode Parts 270
14-Bit Opcode Parts 270
16-Bit Opcode Parts 270
24-Bit Opcode Parts 271
Latency 272
Reentrancy 273
Compatibility Notes 274
Summary 274
Quiz 276
Chapter 18 Timers/Counters 280
Timer Components 280
The Counter Core 280
The Counter Period 280
The Post-scaler 280
The Pre-scaler 281
The Gate 281
The Multiplexer 282
PIC® Specifics 282
C Code 282
Delay Using Timer 284
Precision Loop 285
Interrupts 285
Interrupts at Specific Rates 286
Interrupt at a Specific Time 287
Virtual Timers 288
Summary 289
Quiz 291
Chapter 19 Advanced Timing 294
PWM 294
Capture 298
Compare 300
Compatibility Notes 301
Summary 301
Quiz 303
Chapter 20 Analog Techniques 306
Digital to Analog Conversion 306
Analog to Digital Conversion 308
More than 5.V 311
Filtering 311
Waveform Analysis 315
Aliasing 315
Working in Your Sleep 317
Voltage Reference 317
Comparator 318
Voltage Detect 320
Compatibility Notes 321
Summary 321
Quiz 324
Chapter 21 Internal Serial Busses 326
Serial Peripheral Interface 326
SPI Modes 329
Hardware SPI 329
Multi-drop SPI 330
Fewer Wires 331
Noise 331
Framing Signal 332
Being a Slave 332
I2C 333
Multi-master 337
Special Addresses 338
10-Bit Addresses 338
Slave I2C 339
SMBus 340
Summary 340
Quiz 342
Chapter 22 External Serial Busses 346
RS-232 346
Source Code 348
UART 350
Incoming Data Interrupts 351
Outgoing Data Interrupts 353
Modem Control Signals 354
Hardware Flow Control 355
Software Flow Control 355
Protocol 356
RS-232 Future 357
RS-422 358
RS-485 358
Documentation 359
Summary 360
Quiz 361
Chapter 23 Multitasking 364
Preemptive Scheduling 364
Dispatcher Scheduling 365
Deterministic Scheduling 365
Source Code 366
Semaphores 368
Message Passing 370
await() 370
Task Management 371
Summary 372
Quiz 372
Chapter 24 Inline Assembly 376
Assembly Code with C Code 376
Inline Assembly Code 377
PIC16/PIC18 Simple Move Instructions 377
Accessing C Variables from Assembly 378
PIC16/PIC18 Math Instructions 379
PIC16/PIC18.Bit Instructions 380
PIC16/PIC18 Branch Instructions 380
PIC16/PIC18 Literal Instructions 381
Compiler Modifications to the Assembly 381
SFR Access 382
About the FSR 382
What Not To Do 383
Optimized Assembly 383
PIC24 Instructions 384
dsPIC® Instructions 386
Summary 386
Quiz 387
Chapter 25 Debugging 390
Overview 390
ICSP 391
ICSP Jacks 392
Breakpoints 393
Viewing Memory 395
Stepping 396
Power Debugging 397
Monitor 397
Data Streaming 398
Real-Time Issues 398
Use of a Scope 399
Diagnostic Interface 401
Record/Playback 401
Profile Tool 402
Profiling Code 403
Design Verification 404
Summary 406
Quiz 409
Bibliography 412
Appendix A 32 414
ASCII Chart 414
Appendix B 416
Appendix C 418

Chapter 1

C Overview and Program Structure


Abstract


This chapter explains the structure of C programs as it pertains to embedded microcontrollers. A short example program is used to introduce the reader to each of the basic C elements.

Compilation units (sometimes called translation units), functions, statements, compound statements, expressions, and data declarations are all introduced. The unique C preprocessor concept is covered with some simple preprocessor directive samples. This chapter shows how constants, variables, operators, and function calls make up the basic components of an expression and how they are used together in the C programming language. The basics of functions calls, including passing and returning data, are included.

Examples and exercises are for the popular PIC™ microcontroller manufactured by Microchip.

Keywords

C program structure

Compilation unit

Translation unit

C comments

Functions

Statements

Expressions

Preprocessor

C Source Code


This is what C source code looks like:

This program may look very cryptic to you now. When you have finished reading this book and doing the experiments, this program and much more complex ones will no longer seem cryptic. As you read the next few chapters, you can refer to this program to see how the topics relate to this program. For now, let’s make some observations about the overall look of the program.

Comments


Comments help anyone (including you) who reads your code understand what it does. There are two styles.

Comments between and (can span multiple lines, but may not be nested)

Comments between and end of line (one line only).

The compiler ignores all comments. Both styles are shown in the sample program.

Program Structure


C programs are made up of compilation units, sometimes called translation units. A compilation unit is a set of files that are compiled together by a compiler. For most examples in this book we will be using a single compilation unit. A compilation unit is made up of global data and functions. A function is a callable group of code that in some other languages is referred to as a procedure or subroutine. Functions are made up of local data accessible only to the function and of statements within the function.

C Preprocessor Directives


An interesting feature of C is that it has what is referred to as a preprocessor. Think of the preprocessor as a tool that goes through the code first and makes some modifications to what is actually compiled. Preprocessor directives start with a and occupy the entire line. They will be covered in more detail in Chapter 3. In the above example the directive causes whatever lines are in the file (e3.h) to appear at this spot in the code for the compilation.

For example, if you created a file named delay.inc and put in the file one line:

delay_ms(500);

then you could replace the two delay lines in the above program with and the program would compile exactly the same. In the first step of compilation the compiler preprocessor would read the delay.inc file when it got to that line and replace the #include with where the #include were.

The preprocessor can be a powerful feature in C that can increase program readability, maximize code reuse, and significantly help in program maintenance.

As we examine the sample program shown, you see the first line is a preprocessor directive to include the e3.h file. It is very common for the first non-comment line in a program to include a file with various project- and/or hardware-specific definitions. The .h extension (for header) is frequently used for this kind of file. In our case all the declarations needed for the E3 hardware are in this include file.

Functions


Next we find a function definition for “main”. All programs must have exactly one function named main(). This is where the program begins execution. When referring to a function name in this book we will follow the name with so it is clear that it is a function name. The void before the name indicates this function returns nothing and the void inside the indicates this function gets nothing from the caller. The and are grouping symbols. All functions start and end with these symbols.

Functions will be dealt with in detail in Chapter 7; however, to lay a foundation for what they are, consider some examples of a function being used:

x=sin(y);        sin is a function with one argument and a return value

x=sin(y*3.1415/180);   the argument may be any expression

x=180*sin(y)/3.1415;   the return value may be used in an expression.

Declarations


The “int i” is a data declaration for the variable named with the identifier i. int indicates the variable is an integer. In this case i may only be used inside the main() function. If this line was above the start of the function (outside the function) then i could be accessed by other functions. The range that a variable is accessible from is referred to as the variable scope. Scope will be covered in more detail in Chapter 4.

Statements and Expressions


The line is a statement. Statements are executed at run time. This particular statement has three expressions within. Expressions will be covered in Chapter 5 and statements in Chapter 6. The quick overview of the statement is:

It executes the first expression once       i=1

Repeats the following:

    Tests the second expression and exits the loop if false i<=10

    Executes the statement following the

    The third expression is executed.        i=i+1

In this example the four lines are executed 10 times with the variable i going from 1 to 10 and then, when 11, the loop stops because 11 <= 10 is false.

Expressions are some combination of constants, variables, operators, and function calls. Expressions always have a resulting value. Some simple examples of an operator are and the very special .

In our case since we have four statements to execute in the we need to group them together with the and . This is called a compound statement. The braces may contain zero or more statements. Without those, only the function would be called in the loop 10 times. Then the other three lines would execute once afterwards.

Each of the four lines in our loop is a function call. These functions are not defined by the programmer but rather are functions built into the compiler. Function calls are recognized by the following the function name. The expression(s) inside the of a function call is the data passed into a function. These are called arguments in the call and parameters in the function.

In C a special case of a valid statement is any expression followed by a . Note that just because it is valid does not mean it makes sense. For example, this is a valid C statement:

1+2;

However, it does not do anything. Some compilers might do the addition and that may take some time but nothing more is done. A good compiler will throw a warning on this line because the programmer might have made a typo.

A with no expression before it is a special case of a statement called the null statement. It does nothing.

In C there is not an assignment statement as in some other languages, but rather an assignment operator, the . Consider:

x=3;

This is an expression x = 3 consisting of a variable, operator, and constant. With the it makes a statement. It always assigns the value on the right side (rvalue) to the variable on the left side (lvalue).

Time


The ms in delay_ms is milliseconds. Time units frequently used in programs...

Erscheint lt. Verlag 26.9.2014
Sprache englisch
Themenwelt Mathematik / Informatik Informatik
Technik Bauwesen
Technik Elektrotechnik / Energietechnik
ISBN-10 0-12-801470-9 / 0128014709
ISBN-13 978-0-12-801470-7 / 9780128014707
Haben Sie eine Frage zum Produkt?
PDFPDF (Adobe DRM)
Größe: 50,7 MB

Kopierschutz: Adobe-DRM
Adobe-DRM ist ein Kopierschutz, der das eBook vor Mißbrauch schützen soll. Dabei wird das eBook bereits beim Download auf Ihre persönliche Adobe-ID autorisiert. Lesen können Sie das eBook dann nur auf den Geräten, welche ebenfalls auf Ihre Adobe-ID registriert sind.
Details zum Adobe-DRM

Dateiformat: PDF (Portable Document Format)
Mit einem festen Seiten­layout eignet sich die PDF besonders für Fach­bücher mit Spalten, Tabellen und Abbild­ungen. Eine PDF kann auf fast allen Geräten ange­zeigt werden, ist aber für kleine Displays (Smart­phone, eReader) nur einge­schränkt geeignet.

Systemvoraussetzungen:
PC/Mac: Mit einem PC oder Mac können Sie dieses eBook lesen. Sie benötigen eine Adobe-ID und die Software Adobe Digital Editions (kostenlos). Von der Benutzung der OverDrive Media Console raten wir Ihnen ab. Erfahrungsgemäß treten hier gehäuft Probleme mit dem Adobe DRM auf.
eReader: Dieses eBook kann mit (fast) allen eBook-Readern gelesen werden. Mit dem amazon-Kindle ist es aber nicht kompatibel.
Smartphone/Tablet: Egal ob Apple oder Android, dieses eBook können Sie lesen. Sie benötigen eine Adobe-ID sowie eine kostenlose App.
Geräteliste und zusätzliche Hinweise

Buying eBooks from abroad
For tax law reasons we can sell eBooks just within Germany and Switzerland. Regrettably we cannot fulfill eBook-orders from other countries.

EPUBEPUB (Adobe DRM)

Kopierschutz: Adobe-DRM
Adobe-DRM ist ein Kopierschutz, der das eBook vor Mißbrauch schützen soll. Dabei wird das eBook bereits beim Download auf Ihre persönliche Adobe-ID autorisiert. Lesen können Sie das eBook dann nur auf den Geräten, welche ebenfalls auf Ihre Adobe-ID registriert sind.
Details zum Adobe-DRM

Dateiformat: EPUB (Electronic Publication)
EPUB ist ein offener Standard für eBooks und eignet sich besonders zur Darstellung von Belle­tristik und Sach­büchern. Der Fließ­text wird dynamisch an die Display- und Schrift­größe ange­passt. Auch für mobile Lese­geräte ist EPUB daher gut geeignet.

Systemvoraussetzungen:
PC/Mac: Mit einem PC oder Mac können Sie dieses eBook lesen. Sie benötigen eine Adobe-ID und die Software Adobe Digital Editions (kostenlos). Von der Benutzung der OverDrive Media Console raten wir Ihnen ab. Erfahrungsgemäß treten hier gehäuft Probleme mit dem Adobe DRM auf.
eReader: Dieses eBook kann mit (fast) allen eBook-Readern gelesen werden. Mit dem amazon-Kindle ist es aber nicht kompatibel.
Smartphone/Tablet: Egal ob Apple oder Android, dieses eBook können Sie lesen. Sie benötigen eine Adobe-ID sowie eine kostenlose App.
Geräteliste und zusätzliche Hinweise

Buying eBooks from abroad
For tax law reasons we can sell eBooks just within Germany and Switzerland. Regrettably we cannot fulfill eBook-orders from other countries.

Mehr entdecken
aus dem Bereich
Konzepte, Methoden, Lösungen und Arbeitshilfen für die Praxis

von Ernst Tiemeyer

eBook Download (2023)
Carl Hanser Verlag GmbH & Co. KG
69,99
Konzepte, Methoden, Lösungen und Arbeitshilfen für die Praxis

von Ernst Tiemeyer

eBook Download (2023)
Carl Hanser Verlag GmbH & Co. KG
69,99
Management der Informationssicherheit und Vorbereitung auf die …

von Michael Brenner; Nils gentschen Felde; Wolfgang Hommel …

eBook Download (2024)
Carl Hanser Fachbuchverlag
69,99