Michael Barr - Programming Embedded Systems in C and C++

Здесь есть возможность читать онлайн «Michael Barr - Programming Embedded Systems in C and C++» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Год выпуска: 1999, ISBN: 1999, Издательство: O'Reilly, Жанр: Программирование, Компьютерное железо, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Programming Embedded Systems in C and C++: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Programming Embedded Systems in C and C++»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

This book introduces embedded systems to C and C++ programmers. Topics include testing memory devices, writing and erasing Flash memory, verifying nonvolatile memory contents, controlling on-chip peripherals, device driver design and implementation, optimizing embedded code for size and speed, and making the most of C++ without a performance penalty.

Programming Embedded Systems in C and C++ — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Programming Embedded Systems in C and C++», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

* line character from the serial port and places it in s.

* The newline character is replaced by a null character.

*

* Notes: The caller is responsible for allocating adequate space

* for the string.

*

* Warnings: This function does not block waiting for a newline.

* If a complete string is not found, it will return

* whatever is available in the receive queue.

*

* Returns: A pointer to the string.

* Otherwise, NULL is returned to indicate an error.

*

**********************************************************************/

char * SerialPort::gets(char * s) {

char * p;

int c;

//

// Read characters until a newline is found or no more data.

//

for (p = s; (c = getchar()) != '\n' && c >= 0; p++) {

*p = c;

}

//

// Terminate the string.

//

*p = '\0';

return (s);

} /* gets() */

9.5 The Zilog 85230 Serial Controller

The two serial ports on the arcom board are part of the same zilog 85230 serial communications Controller. This particular chip is, unfortunately, rather complicated to configure and use. So, rather than fill up the SerialPort class shown earlier with device-specific code, I decided to divide the serial driver into two parts. The upper layer is the class we have just discussed. This upper layer will work with any two-channel SCC that provides byte-oriented transmit and receive interfaces and configurable baud rates. All that is necessary is to implement a device-specific SCC class (the lower layer described next) that has the same reset , init , txStart , and rxStart interfaces as those called from the SerialPort class.

In fact, one of the reasons the Zilog 85230 SCC device is so difficult to configure and use is that it has many more options than are really necessary for this simple application. The chip is capable of sending not only bytes but also characters that have any number of bits up to 8. And in addition to being able to select the baud rate, it is also possible to configure many other features of one or both channels and to support a variety of other communication protocols.

Here's how the SCC class is actually defined:

#include "circbuf.h"

class SCC {

public:

SCC();

void reset(int channel);

void init(int channel, unsigned long baudRate, CircBuf * pTxQueue, CircBuf * pRxQueue);

void txStart(int channel);

void rxStart(int channel);

private:

static void interrupt Interrupt(void);

};

Notice that this class also depends upon the CircBuf class. The pTxQueue and pRxQueue arguments to the init method are used to establish the input and output buffers for that channel. This makes it possible to link a logical SerialPort object with one of the physical channels within the SCC device. The reason for defining the init method separately from the constructor is that most SCC chips control two or more serial channels. The constructor resets them both the first time it is called. Then, init is called to set the baud rate and other parameters for a particular channel.

Everything else about the SCC class is an internal feature that is specific to the Zilog 85230 device. For that reason, I have decided not to list or explain this rather long and complex module within the book. Suffice it to say that the code consists of macros for reading and writing the registers of the device, an interrupt service routine to handle receive and transmit interrupts, and methods for restarting the receive and transmit processes if they have previously stalled while waiting for more data. Interested readers will find the actual code in the file scc.cpp .

Chapter 10. Optimizing Your Code

Things should be made as simple as possible, but not any simpler.

Albert Einstein

Though getting the software to work correctly seems like the logical last step for a project, this is not always the case in embedded systems development. The need for low-cost versions of our products drives hardware designers to provide just barely enough memory and processing power to get the job done. Of course, during the software development phase of the project it is more important to get the program to work correctly. And toward that end there are usually one or more "development" boards around, each with additional memory, a faster processor, or both. These boards are used to get the software working correctly, and then the final phase of the project becomes code optimization. The goal of this final step is to make the working program run on the lower-cost "production" version of the hardware.

10.1 Increasing Code Efficiency

Some degree of code optimization is provided by all modern C and C++ compilers. However, most of the optimization techniques that are performed by a compiler involve a tradeoff between execution speed and code size. your program can be made either faster or smaller, but not both. In fact, an improvement in one of these areas can have a negative impact on the other. It is up to the programmer to decide which of these improvements is most important to her. Given that single piece of information, the compiler's optimization phase can make the appropriate choice whenever a speed versus size tradeoff is encountered.

Because you can't have the compiler perform both types of optimization for you, I recommend letting it do what it can to reduce the size of your program. Execution speed is usually important only within certain time-critical or frequently executed sections of the code, and there are many things you can do to improve the efficiency of those sections by hand. However, code size is a difficult thing to influence manually, and the compiler is in a much better position to make this change across all of your software modules.

By the time your program is working you might already know, or have a pretty good idea, which subroutines and modules are the most critical for overall code efficiency. Interrupt service routines, high-priority tasks, calculations with real-time deadlines, and functions that are either compute-intensive or frequently called are all likely candidates. A tool called a profiler , included with some software development suites, can be used to narrow your focus to those routines in which the program spends most (or too much) of its time.

Once you've identified the routines that require greater code efficiency, one or more of the following techniques can be used to reduce their execution time:

Inline functions

In C++, the keyword inline can be added to any function declaration. This keyword makes a request to the compiler to replace all calls to the indicated function with copies of the code that is inside. This eliminates the runtime overhead associated with the actual function call and is most effective when the inline function is called frequently but contains only a few lines of code.

Inline functions provide a perfect example of how execution speed and code size are sometimes inversely linked. The repetitive addition of the inline code will increase the size of your program in direct proportion to the number of times the function is called. And, obviously, the larger the function, the more significant the size increase will be. The resulting program runs faster, but now requires more ROM.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Programming Embedded Systems in C and C++»

Представляем Вашему вниманию похожие книги на «Programming Embedded Systems in C and C++» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Programming Embedded Systems in C and C++»

Обсуждение, отзывы о книге «Programming Embedded Systems in C and C++» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x