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++», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

if ((baseAddress[offset] != pattern) && (offset != testOffset)) {

return ((datum *) &baseAddress[testOffset]);

}

}

baseAddress[testOffset] = pattern;

}

return (NULL);

} /* memTestAddressBus() */

6.2.2.3 Device test

Once you know that the address and data bus wiring are correct, it is necessary to test the integrity of the memory device itself. The thing to test is that every bit in the device is capable of holding both and 1. This is a fairly straightforward test to implement, but it takes significantly longer to execute than the previous two.

For a complete device test, you must visit (write and verify) every memory location twice. You are free to choose any data value for the first pass, so long as you invert that value during the second. And because there is a possibility of missing memory chips, it is best to select a set of data that changes with (but is not equivalent to) the address. A simple example is an increment test.

The data values for the increment test are shown in the first two columns of Table 6-3. The third column shows the inverted data values used during the second pass of this test. The second pass represents a decrement test. There are many other possible choices of data, but the incrementing data pattern is adequate and easy to compute.

Table 6-3. Data Values for an Increment Test

Memory Offset Binary Value Inverted Value
000h 00000001 11111110
001h 00000010 11111101
002h 00000011 11111100
003h 00000100 11111011
0FEh 11111111 00000000
0FFh 00000000 11111111

The function memTestDevice implements just such a two-pass increment/decrement test. It accepts two parameters from the caller. The first parameter is the starting address, and the second is the number of bytes to be tested. These parameters give the user a maximum of control over which areas of memory will be overwritten. The function will return NULL on success. Otherwise, the first address that contains an incorrect data value is returned.

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

*

* Function: memTestDevice()

*

* Description: Test the integrity of a physical memory device by

* performing an increment/decrement test over the

* entire region. In the process every storage bit

* in the device is tested as a zero and a one. The

* base address and the size of the region are

* selected by the caller.

*

* Notes:

*

* Returns: NULL if the test succeeds. Also, in that case, the

* entire memory region will be filled with zeros.

*

* A nonzero result is the first address at which an

* incorrect value was read back. By examining the

* contents of memory, it may be possible to gather

* additional information about the problem.

*

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

datum * memTestDevice(volatile datum * baseAddress, unsigned long nBytes) {

unsigned long offset;

unsigned long nWords = nBytes / sizeof(datum);

datum pattern;

datum antipattern;

/*

* Fill memory with a known pattern.

*/

for (pattern = 1, offset = 0; offset < nWords; pattern++, offset++) {

baseAddress[offset] = pattern;

}

/*

* Check each location and invert it for the second pass.

*/

for (pattern = 1, offset = 0; offset < nWords; pattern++, offset++) {

if (baseAddress[offset] != pattern) {

return ((datum *) &baseAddress[offset]);

}

antipattern = ~pattern;

baseAddress[offset] = antipattern;

}

/*

* Check each location for the inverted pattern and zero it.

*/

for (pattern = 1, offset = 0; offset < nWords; pattern++, offset++) {

antipattern = ~pattern;

if (baseAddress[offset] != antipattern) {

return ((datum *) &baseAddress[offset]);

}

baseAddress[offset] = 0;

}

return (NULL);

} /* memTestDevice() */

6.2.2.4 Putting it all together

To make our discussion more concrete, let's consider a practical example. Suppose that we wanted to test the second 64-kilobyte chunk of the SRAM on the Arcom board. To do this, we would call each of the three test routines in turn. In each case, the first parameter would be the base address of the memory block. Looking at our memory map, we see that the physical address is 10000h, which is represented by the segment:offset pair 0x1000:0000 . The width of the data bus is 8 bits (a feature of the 80188EB processor), and there are a total of 64 kilobytes to be tested (corresponding to the rightmost 16 bits of the address bus).

If any of the memory test routines returns a nonzero (or non- NULL ) value, we'll immediately turn on the red LED to visually indicate the error. Otherwise, after all three tests have completed successfully, we will turn on the green LED. In the event of an error, the test routine that failed will return some information about the problem encountered. This information can be useful when communicating with a hardware engineer about the nature of the problem. However, it is visible only if we are running the test program in a debugger or emulator.

The best way to proceed is to assume the best, download the test program, and let it run to completion. Then, if and only if the red LED comes on, must you use the debugger to step through the program and examine the return codes and contents of the memory to see which test failed and why.

#include "led.h"

#define BASE_ADDRESS (volatile datum *) 0x10000000

#define NUM_BYTES 0x10000

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

*

* Function: main()

*

* Description: Test the second 64 KB bank of SRAM.

*

* Notes:

*

* Returns: 0 on success.

* Otherwise -1 indicates failure.

*

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

main(void) {

if ((memTestDataBus(BASE_ADDRESS) != 0) || (memTestAddressBus(BASE_ADDRESS, NUM_BYTES) != NULL) || (memTestDevice(BASE_ADDRESS, NUM_BYTES) != NULL)) {

toggleLed(LED_RED);

return (-1);

} else {

toggleLed(LED_GREEN);

return (0);

}

} /* main() */

Unfortunately, it is not always possible to write memory tests in a high-level language. For example, C and C++ both require the use of a stack. But a stack itself requires working memory. This might be reasonable in a system that has more than one memory device. For example, you might create a stack in an area of RAM that is already known to be working, while testing another memory device. In a common such situation, a small SRAM could be tested from assembly and the stack could be created there afterward. Then a larger block of DRAM could be tested using a nicer test algorithm, like the one shown earlier. If you cannot assume enough working RAM for the stack and data needs of the test program, then you will need to rewrite these memory test routines entirely in assembly language.

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

Интервал:

Закладка:

Сделать

Похожие книги на «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